Search code examples
javascriptnode.jsmongodbunset

How to remove specific data within a field in mongodb


I have this posts collection:

{
    id: 'post_id',
    content: 'text here',
    postedBy: 'user_id',
    likes: [
        {
            0: 'user_id
        },
        {
            1: 'another_user_id'
        }
    ]
}

I would like to be able to delete all likes by a specific user across all posts. I have tried using the $unset operator like this:

const likes = await Post.updateMany({ $unset: { likes: user_id } });

And like this:

const likes = await Post.updateMany(
    { likes: user_id },
    { $unset: { likes: '' } }
);

However what these both do is remove all the likes from posts that contain a like by this user.

Does anybody know how I can only remove the likes that one particular user has made?


Solution

  • The answer was to use $pull instead of $unset:

    const likes = await Post.updateMany({ $pull: { likes: u._id } });