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 using 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?
User.findOneAndUpdate
first. That will ensure the count is already modified when theUser.findOne
is executed. At the minute yourUser.findOne
retrieves the original state, holds it an a variable, meanwhile you modify the database with theUser.findOneAndUpdate
. Your variable doesn't know the database has just been updated on the side. You then overwrite those changes with theuser.save()
.const user = await User.findOneAndUpdate
returns anull
(no user found) in the first place. Then you can return from the function as everything else is irrelevant.