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?
To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.
Adding Subdocs to Arraysconst Parent = mongoose. model('Parent'); const parent = new Parent(); // create a comment parent. children. push({ name: 'Liesl' }); const subdoc = parent.
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}
)
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
});
});
User.findOneAndUpdate({ _id: "12346" }, { $pull: { event: { _id: "12346" } } }, { new: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With