Elamparithi.P
Elamparithi.P

Reputation: 149

How to remove the nested array object value with its Object ID in Mongoose?

i need to delete the url from the below mongodb database with the id which is in url object, then need the remaining data's as a result

My mongodb collection has the following :

    {
      "_id" : ObjectId("589b043abc2f5a467c13303b"),
      "user_id" : ObjectId("5874c174c813822341cb59a7"),
      "filename" : [
       {
         "url" : "images/product_images/file-1486554170465.jpeg",
         "_id" : ObjectId("589b043abc2f5a467c13303c")
       },
       {
         "url" : "images/product_images/file-1486554306440.jpeg",
         "_id" : ObjectId("589b04c2bc2f5a467c13303f")
       }]
    }

Can anybody help me please , thanks in advance ..

Upvotes: 0

Views: 795

Answers (1)

Jyotman Singh
Jyotman Singh

Reputation: 11350

In mongoose you can do this -

CollectionInstance.findByIdAndUpdate(documentId, {
    $pull: {
        filename: {_id: urlId}
    }
}, {new: true});

By documentId I mean 589b043abc2f5a467c13303b and by urlId I mean 589b043abc2f5a467c13303c in your above example code.

What we are doing here finding is the particular document in the collection through its _id and then pulling the particular document from the filename array through its _id.

The {new: true} option tells Mongo to return the updated document. By default this value is false and Mongo returns the document state before update.

Upvotes: 1

Related Questions