Reputation: 814
This is my first web application and I need to delete a nested array item. How would you delete an object in Mongoose with this schema:
User: {
event: [{_id:12345, title: "this"},{_id:12346, title:"that"}]
}
How can I go about deleting id:12346
in mongoose/Mongo?
Upvotes: 11
Views: 12344
Reputation: 31
User.findOneAndUpdate({ _id: "12346" }, { $pull: { event: { _id: "12346" } } }, { new: true });
Upvotes: 2
Reputation: 3266
Use $pull to remove items from an array of items like below :
db.User.update(
{ },
{ $pull: { event: { _id: 12346 } } }
)
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Empty object in the first parameter is the query
to find the documents. The above method removes the items with _id: 12345
in the event
array in all the documents in the collection.
If there are multiple items in the array that would match the condition, set multi
option to true as shown below :
db.User.update(
{ },
{ $pull: { event: { _id: 12346 } } },
{ multi: true}
)
Upvotes: 17
Reputation: 3384
Findone will search for id,if not found then err otherwise remove will work.
User.findOne({id:12346}, function (err, User) {
if (err) {
return;
}
User.remove(function (err) {
// if no error, your model is removed
});
});
Upvotes: 1