Search code examples
mongodbmongoosemongoose-schema

How to increment filed in mongodb mongoose


 const options = {
    $addToSet: { whoLikes: userId },
    $inc: { likesCount: 1 },
    new: true,
  };

collection.findByIdAndUpdate({ _id: postId }, options)

What I want is increment likesCount only if whoLikes array length is get incremented. Right now likesCount incrementing all the time doesn't matter how many objects inside whoLikes array.

I'm using mongoose, node.js


Solution

    • use findOneAndUpdate() method
    • Just check condition in your query part whoLikes: { $ne: userId } userId should not inside whoLikes array
    • user $push instead of $addToSet
    • other options should be in third parameter new:true
    const options = {
        $push: { whoLikes: userId },
        $inc: { likesCount: 1 }
    };
    
    collection.findOneAndUpdate(
      { 
        _id: postId,
        whoLikes: { $ne: userId }
      }, 
      options,
      { new: true }
    )
    

    Ex1: Add UserID that is not present

    Playground

    Ex2: Add UserID that is already present

    Playground