问题
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