Node Js and Moongoose: How to loop into array of objects and delete a particular object and then update the whole document

Viewed 37

My document schema is as follows:

 const CollectionSchema = mongoose.Schema({
   ImageCategory:{type:String,required:true},
   imgDetails: [
       {
           _id: false,
           imageUrl:{type:String},
           imageName:{type:String},
           imageMimeType:{type:String},
       }
   ],
   Date: {
      type: String,
      default: `${year}-${month}-${day}`,
   },
},{timestamps: true,})

So in the database for example one document has multiple images with a single image category. What I am trying to do is I want to delete an object from imgDetails array.

Let me explain my question more precisely: imgDetails is an array

Explanation: I want to loop in imgDetails and then find (where imgageUrl === req.body.imageUrl) if its match delete that whole object which have that req.body.imageUrl and then update the document.

Please guide me on how to write such a query. Regards

1 Answers

Demo - https://mongoplayground.net/p/qpl7lXbKAZE

Use $pull

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

db.collection.update(
  {},
  { $pull: { "imgDetails": { imageUrl: "xyz" } } }
)
Related