0

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?

2
  • You simply need to switch the order of your query. I'm not sure why you are doing two queries in the first place but to get the desired result do the User.findOneAndUpdate first. That will ensure the count is already modified when the User.findOne is executed. At the minute your User.findOne retrieves the original state, holds it an a variable, meanwhile you modify the database with the User.findOneAndUpdate. Your variable doesn't know the database has just been updated on the side. You then overwrite those changes with the user.save().
    – jQueeny
    Commented Jul 10 at 7:15
  • You really should be checking if const user = await User.findOneAndUpdate returns a null (no user found) in the first place. Then you can return from the function as everything else is irrelevant.
    – jQueeny
    Commented Jul 10 at 7:18

1 Answer 1

1

Because of this user local variable

const user= await User.findOne({username:"ravi"});
console.log(user); // count = 0 

You are getting user before findOneAndUpdate so count will be 0 initially. Then incrementing and save would give you 1 as count.

So you have to increment the local count value for findOneAndUpdate

async function helper(){

    //retriving user data from Db
    const user=await User.findOne({username:"ravi"});
    console.log(user);

    //updating using findoneAndUpdate and increment the local variable
    await User.findOneAndUpdate({username:"ravi"},{$inc:{count:1}}).then(()=> (++user.count));
    
    
    //updating using save
    user.count++;
    const updatedUser=await user.save();
    console.log(updatedUser);

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.