首页 > 解决方案 > 如果存在,如何更新文档,如果在 mongodb 中不存在,如何将其插入?

问题描述

这个问题与其他类似问题不同,因为 { upsert: true } 选项没有提供所需的输出。我想更新/插入以下文档:

{
  _id: { 
    playerId: '1407081',
    tournamentId: '197831',
    matchId: '1602732' 
  },
  playerName: 'abcd',
  points: -5
}

执行下面给出的代码后,

await Points.findOneAndUpdate(
  {
    "_id": playerStatsObjForDB._id
  }, 
  {
    playerStatsObjForDB
  }, 
  {
    upsert: true
  }
);
//where playerStasObjForDB is same as object mentioned in top.

如果文档不存在,则插入以下文档:

{
  "_id": {
    "playerId":"1407081",
    "tournamentId":"197831",
    "matchId":"1602732"
  },
  "__v":0,
}

我正在使用猫鼬,但非常感谢任何帮助。

标签: node.jsmongodbmongoosemongodb-query

解决方案


MongoDB upsert 的工作方式如下:

    db.products.updateMany(
    { _id: 6 },
    { $set: {price: 999} },
    { upsert: true}
)

所以基本上第一个参数是查询本身,就像你做的一样,但第二个应该是你想要修改的更新,你应该使用像 $set 这样的 MongoDB 运算符。相反,您似乎将整个对象嵌入其中而没有修改。


推荐阅读