Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove nested objects from an array in Mongoose

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?

like image 577
illcrx Avatar asked Jan 02 '17 17:01

illcrx


People also ask

How do I delete a nested file in MongoDB?

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.

How to add subdocument in mongoose?

Adding Subdocs to Arraysconst Parent = mongoose. model('Parent'); const parent = new Parent(); // create a comment parent. children. push({ name: 'Liesl' }); const subdoc = parent.


3 Answers

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}
)
like image 133
Supradeep Avatar answered Oct 18 '22 17:10

Supradeep


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
        });
    });
like image 33
Codesingh Avatar answered Oct 18 '22 17:10

Codesingh


User.findOneAndUpdate({ _id: "12346" }, { $pull: { event: { _id: "12346" } } }, { new: true });
like image 2
BILAL ARIF Avatar answered Oct 18 '22 17:10

BILAL ARIF