简体   繁体   中英

How to update document if it exist and insert it if it doesn't exist in mongodb?

This question is different from other similar questions because { upsert: true } option doesn't give desired output. I want to update/insert the given below document:

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

After executing the given below code,

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

if the document doesn't exist, it inserts the following document:

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

I am using mongoose, but any help is greatly appreciated.

Well MongoDB upsert works in the following way:

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

So basically the first parameter is the query itself the same way you did, but the second one should be the updates you want to modify and you should use MongoDB operators like $set. Instead, it seems that you embedded the entire object inside it without modifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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