所以我想要做的是添加到文档中的对象而不是删除整个事物。我有一个包含数组的文档,如果我调用findOneAndUpdate,它会添加我想要的内容,但会删除数组中已有的所有内容。
我想做的就是保留我已经拥有的数组并添加一个项目。
这是我的代码:
Friends.findOneAndUpdate({facebookId: value.id}, {$set: {friends: {id: profile.id, name: profile._json.name}} }, {new: false}, function (err, friends) {
if(err){
console.log("Something went wrong when updating data!");
}
console.log("success saving user friend update");
});
以下是我的数组在数据库中发生的事情:
此:
"friends": [
{
"id": "114222474148205",
"name": "Chris Chang"
},
{
"id": "903622474147290",
"name": "Johny Unitas"
},
{
"id": "685034985392094",
"name": "Mary Jane"
}
]
对此:
"friends": {
"id": "49572957395733524",
"name": "John Doe"
}
我想要的是那两个要合并。
那么我如何“添加”一个项目而不是“更新”该项目呢?
答案 0 :(得分:2)
正如若昂所说;我所要做的就是将$ set改为$ push。
所以这个:
Friends.findOneAndUpdate({facebookId: value.id}, {$push: {friends: {id: profile.id, name: profile._json.name}} }, {new: false}, function (err, friends) {
而不是:
Friends.findOneAndUpdate({facebookId: value.id}, {$set: {friends: {id: profile.id, name: profile._json.name}} }, {new: false}, function (err, friends) {