I’m having an issue with updating a user’s count field in MongoDB using Mongoose. Here is my schema and the code I’m using:
const user=new Schema({
username:String,
count:{
type:Number,
default:()=>0
}
},{
optimisticConcurrency:true
});
async function helper(){
//retriving user data from Db
const user=await User.findOne({username:"ravi"});
console.log(user);
//updating useing findoneAndUpdate
await User.findOneAndUpdate({username:"ravi"},{$inc:{count:1}});
//updating using save
user.count+=1;
const updatedUser=await user.save();
console.log(updatedUser);
}
When I first update the user with findOneAndUpdate(), the count field is increased by 1. Then, when I update the user with save(), the count should increase by 1 again. The total count should be increased by 2, but it only increases by 1. How can I ensure the count field is updated correctly?