简体   繁体   中英

How can I use findOneAndUpdate() in Mongoose, and keep a value the same?

I'm making a system that will increment value1 if x is true, but if y is true it will increment value2. Using the system I have now, it will also reset the value that is not being updated back to 0, I don't know what to do to stop this. I just need the other value to be the same

Here is my code.

leaderboard.findOneAndUpdate(
{ 
    userID: interaction.user.id 
}, 
{
    userID: interaction.user.id,
    $inc: { accepts: 1 },
    denies: 0
}, 
{ 
    upsert: true, new: true 
},  (err: any, doc: any) => {

if (err) console.log(err)

console.log(`Updated ${interaction.user.username}'s accepts to ${doc.accepts} `)
})

So in this example, I need accepts to be incremented by 1, but declines to stay the same that is already in the MongoDB.

Try changing your update query to this

{ $inc: { accepts: 1 } }

Not sure if upsert makes sense in that case. Because it would create a new document with only the accepts field.

{ upsert: true, new: true }

If upsert is needed then build your update query based on the value to set. Eg

If (x) {
  updateQuery = {
    userID: interaction.user.id,
    $inc: { accepts: 1 },
  }
} else {
  updateQuery = {
    userID: interaction.user.id,
    $inc: { denies: 1 },
  }
}

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