UAhmadSoft
UAhmadSoft

Reputation: 141

Update a value inside document using document's value in findOneAndUpdateQuery- Mongoose

I have a user scheme like this


const userSchema = new mongoose.Schema(
  { 
    name: {
      type: String,
    },
    points: Number
}

I want to update the user's points using the current user's points i.e user.points += 100 or like this In query

await User.findByIdAndUpdate( userId , 
      { loyaltyPoints :  user.loyaltyPoints + 100}
      , {new  :true, runValidator :true} )

Upvotes: 0

Views: 19

Answers (1)

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1492

Since points is a number, you can use MongoDB $inc which is specifically design for this purpose. So a += 100 would be

{
  $inc: {
    points: 100
  }
}

Upvotes: 1

Related Questions