3

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.

Here is what the User model looks like:

(I am not explicitly putting an _id field it is assigned one automatically)

    let userSchema = new mongoose.Schema({
    id: String,
    displayName: String,
    posts: [
        {
            url: String,
            description: String,
            likes: [String]
        }
    ]
    });

Why is this happening and what is a possible solution?

JohnSnow
  • 6,911
  • 8
  • 23
  • 44
  • 1
    When I do a similar operation I only use '_id' instead of 'posts._id' when I point to which object to pull. – tomtom Apr 12 '17 at 08:32
  • 1
    Based on the marked dupe, your update query should be `User.findOneAndUpdate( { id: req.params.userid }, { $pull: { 'posts': { _id': req.body.postID } } }, { new: true } )` – chridam Apr 12 '17 at 08:32
  • Ok that does work, would you care to explain though why my query as it stands removes ALL objects? what is the reasoning behind that? – JohnSnow Apr 12 '17 at 08:34
  • 1
    I believe the culprit is the update statement `{ $pull: { 'posts': { 'posts._id': { $eq: req.body.postID } } } },` which is pulling all posts as the `posts` array does not have any document with the key `posts._id`. Read more [here](https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents). – chridam Apr 12 '17 at 08:40
  • @chridam makes sense thanks – JohnSnow Apr 12 '17 at 08:47

0 Answers0