簡體   English   中英

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

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

所以我要做的是添加到文檔中的一個對象上而不是刪除整個對象。 我有一個帶有數組的文檔,如果我調用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"
}

我想要的是將兩者結合起來。

那么,我將如何“添加”項目而不是“更新”該項目?

如Joao所說: 我要做的就是將$ 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) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM