Wednesday, 12 April 2017

$pulling an object from an array based on _id in Mongoose

I am trying to delete an object from an array based on its _id field like so:

(posts is an array of objects)

    User.findOneAndUpdate(
    { id: req.params.userid },
    { $pull: { 'posts': { 'posts._id': { $eq: req.body.postID } } } },
    { new: true }
 )

However, it is deleting ALL posts in the array even though they have different _id values referenced by req.body.postID.

Note: If i try this same query with a different field like the post's name, then it works just fine and deletes just that post. However I need to do this by _id field to ensure uniqueness.

Why is this happening and what is a possible solution?



via JohnSnow

No comments:

Post a Comment