Array.push does not seem to work on MongoDB

杀马特。学长 韩版系。学妹 提交于 2021-01-28 02:22:21

问题


I would like to create a dynamic vector/array in MongoDB. The idea is simple: whenever someone submits something, it should update a user in my database in MongoDB. I have created a variable for that. I have already tested: the proper user is found correctly.

Please, find it a snippet of my code.

User.findOne({ name })
          .then(user => {                
            user.something.push(something to push);
          })

I have set the default value when it is created as empty:

  something: {   
    type: [String],
    default: []
  }

However, it does not save, and throw no error. Anyone has a guess of what might be happening behind the scenes? I am new to MongoDB.


回答1:


You can use findOneAndUpdate() with $push mongodb operator

User.findOneAndUpdate({name:name},{$push:{ something: 'new_data'}});



回答2:


You need to update the database with another call.

User.findOne({ name })
    .then(user => {                
        user.something.push(something to push);
        User.update({{ _id: user._id }})
    })

Or you can directly use

User.findOneAndUpdate({ name }, { something: ['new_data']});


来源:https://stackoverflow.com/questions/58432171/array-push-does-not-seem-to-work-on-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!