简体   繁体   English

使用Mongoose更新MongoDB文档而不删除文档中已有的信息

[英]Updating a MongoDB document with Mongoose without removing the information already in the document

So what I want to do is add on to an object in the document not delete the whole thing. 所以我要做的是添加到文档中的一个对象上而不是删除整个对象。 I have a document with an array in it and if I call findOneAndUpdate it adds what I want but gets rid of everything already in the array. 我有一个带有数组的文档,如果我调用findOneAndUpdate,它会添加我想要的内容,但会删除数组中已有的所有内容。

All I want to do is keep what I already have in my array and add one more item. 我要做的就是保留数组中已有的内容,再添加一项。

Here is my code: 这是我的代码:

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");
});

And here is what happens with my array in the database: 这是我在数据库中的数组发生的情况:

This: 这个:

"friends": [
    {
        "id": "114222474148205",
        "name": "Chris Chang"
    },
    {
        "id": "903622474147290",
        "name": "Johny Unitas"
    },
    {
        "id": "685034985392094",
        "name": "Mary Jane"
    }
]

To this: 对此:

"friends": {
    "id": "49572957395733524",
    "name": "John Doe"
}

What I want is those two to be combined. 我想要的是将两者结合起来。

So how would I "add" an item and not "update" the item? 那么,我将如何“添加”项目而不是“更新”该项目?

As Joao said above; 如Joao所说: all I you have to do is change $set to $push. 我要做的就是将$ set更改为$ push。

So this: 所以这:

Friends.findOneAndUpdate({facebookId: value.id}, {$push: {friends: {id: profile.id, name: profile._json.name}} }, {new: false}, function (err, friends) {

instead of this: 代替这个:

Friends.findOneAndUpdate({facebookId: value.id}, {$set: {friends: {id: profile.id, name: profile._json.name}} }, {new: false}, function (err, friends) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM