Search code examples
mongodbmongoosemongodb-querymongoose-schema

mongoose updateOne function: don't update if $pull didn't work


I'm using updateOne method like this:

Photo.updateOne(
    {
        "_id": photoId
    },
    {
        "$pull": {
            comments: {
                _id: ObjectID(commentId),
                "user.id": user.id
            }
        },
        "$inc": { "commentCount": -1 },
    },
)

Photo model which contains comments as a array and commentCount as a number. When I run the code it's working but if the photo doesn't have the comment (which I'm trying to pull) it's still incrementing commentCount by -1. What I want is, if the code does not pull any comment in photo comments, don't update the commentCount too. How can I add this rule to my code?

Thanks for help.


Solution

  • You can also add both fields comments._id and comments.use.id conditions in query part, if comment is not available then it will skip update and pull part.

    Photo.updateOne(
        { 
            _id: photoId,
            comments: {
                $elemMatch: {
                    _id: ObjectID(commentId),
                    "user.id": user.id
                }
            }
        },
        {
            "$pull": {
                comments: {
                    _id: ObjectID(commentId),
                    "user.id": user.id
                }
            },
            "$inc": { "commentCount": -1 }
        }
    )