温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - MongoDB update object in array if exists or push

node.js - MongoDB更新数组中的对象(如果存在或推送)

发布于 2020-03-27 15:41:11

我在数据库中有对象,它们有一个评分对象数组,如果用户的ID已经在这些对象中,则需要更新速率,如果没有,则用速率用户 ID 将新对象添加到数组中

文件图片:

在此处输入图片说明

代码:

router.post('/rating', (req, res) => {
 // console.log(req.body)
  let ID = 'f58482b1-ae3a-4d8a-b53b-ede80fe1e225';
  // let user = '5e094d988ddbe02020e13879';
  let user = 'asdadasdasd';
  Habalka.find({
      _id: ID
    },
    {rating: {$elemMatch: {user}}})
    .then(res => {
      if (res[0].rating.length) {
        // Habalka.updateOne(
        //   {
        //     _id: ID,
        //     'rating.user': user
        //   },
        //   {$inc:{"rating.$.rate.1":10}}
        // )
        //   .then(resUpdate => {
        //     console.log(resUpdate)
        //   })
        // **HERE I need to update rate if the user is already there**
      } else {
        // **HERE if there is no user, I need to insert an object with it and rate**
      }
    });
  // console.log(req)
});

JSON文档:

{ 
  "_id":"f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
   "bio":{ 
      "firstname":"Лена",
      "lastname":"фыв",
      "middlename":"",
      "company":"вв"
   },
   "files":[ 
      { 
         "_id":"2e4e40c7-4df6-4974-8d16-bb24cd8134d6",
         "destination":"./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
         "filename":"2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
         "path":"uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
         "folder":"f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
         "info":{ 
            "size":20805727,
            "mimetype":"audio/mp3",
            "encoding":"7bit",
            "originalname":"Ахуевший Ленусик (Банк русский стандарт). Выпуск #5..mp3",
            "fieldname":"selectedFile"
         },
         "userId":"5e05da745b21e61ccc84a892",
         "date":"2019-12-27T10:19:12.213Z",
         "guessId":{ 
            "f58482b1-ae3a-4d8a-b53b-ede80fe1e225":[ 
               "5e05da745b21e61ccc84a892",
               "5e094d988ddbe02020e13879"
            ],
            "b7d00dea-c872-43f4-b193-8454bef5cf85":[ 

            ]
         }
      },
      { 
         "_id":"81b94dea-ece6-421c-b68a-0aa59332cd0d",
         "destination":"./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
         "filename":"81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
         "path":"uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
         "folder":"f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
         "info":{ 
            "size":13515683,
            "mimetype":"audio/mp3",
            "encoding":"7bit",
            "originalname":"Выпуск #75 Попрошайка НСВ..mp3",
            "fieldname":"selectedFile"
         },
         "userId":"5e05da745b21e61ccc84a892",
         "date":"2019-12-27T10:25:37.710Z",
         "guessId":{ 
            "b7d00dea-c872-43f4-b193-8454bef5cf85":[ 
               "5e05da745b21e61ccc84a892",
               "5e094d988ddbe02020e13879"
            ],
            "f58482b1-ae3a-4d8a-b53b-ede80fe1e225":[ 

            ]
         }
      }
   ],
   "date":"2019-12-27T10:19:12.213Z",
   "__v":1,
   "rating":[ 
      { 
         "rate":4,
         "user":"5e094d988ddbe02020e13879"
      },
      { 
         "rate":3,
         "user":"asdadasdasd"
      }
   ]
}

查看更多

查看更多

提问者
Стас Рябцев
被浏览
60
whoami 2020-01-31 16:06

您可以尝试.bulkWrite()

Habalka.bulkWrite([{
    updateOne: {
        "filter": { "rating.user": "asdadasdasd" },
        "update": { $set: { "rating.$.rate": 13 } } // Will update rate
    }
},
{
    updateOne: {
        "filter": { "rating.user": { $ne: "asdadasdasd" } },
        "update": { $push: { "rating": { "user": "asdadasdasd", "rate": 13 } } } // will push new object to rating
    }
}])

在任何给定的情况下,从上述两个中updateOne只有一个将写入数组rating

发布
问题

分享
好友

手机
浏览

扫码手机浏览