$ pulling object from array based on _id in Mongoose
I am trying to remove an object from an array based on its _id field like this:
(messages are an array of objects)
User.findOneAndUpdate(
{ id: req.params.userid },
{ $pull: { 'posts': { 'posts._id': { $eq: req.body.postID } } } },
{ new: true }
)
However, it removes ALL entries in the array, even if they have different _id values ββbeing referenced req.body.postID
.
Note. ... If I try this same query with a different field, for example named post, then it works fine and only deletes that post. However, I need to do this with an _id field to ensure uniqueness.
This is what the model looks like User
:
(I don't explicitly set the _id field, which is automatically assigned to it)
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?
source to share
No one has answered this question yet
See similar questions:
or similar: