1

Is there a way to remove sub-document from object without passing the parentId? So I have a document which looks like this:

name: {
  type: [String],
  trim: true,
  required: [true, 'Please add your name']
},
experience: [
  {
    title: {
      type: String,
      trim: true,
      required: [true, 'Please add an experience title']
    }
  }
],

Each of this document can have several objects in the experience array.

Adding and updating has been easy for me because I usually just need to pass the Id of the parent document.

Now I would like to delete any object of said experience array by proving only its id...not the parentId.

Hopefull this code can help explain what I'm looking for:

  const resume = await Resume.findByIdAndUpdate(
    {
      // _id: req.params.id, // <=== is the parent id...
      experience: { _id: req.params.exp_id }
    },
    {
      $pull: { experience: { _id: req.params.exp_id } }
    },
    {
      new: true,
      runValidators: true
    }
  );

You can see in the code above that I passed the _id of the parent document which if I continue this way, it works great but for my needs I need to only pass the _id of the subdocument.

Is that actually possible?

Kirasiris
  • 523
  • 10
  • 37
  • 1
    I think all you need to do is use `update` or `updateOne` instead of `findByIdAndUpdate`. – ippi Aug 21 '20 at 04:20
  • 1
    So, there is a exp_id in `experience` sub-document? Like: experience: [ {exp_id: String, title: { type: String, trim: true, required: [true, 'Please add an experience title'] } } ] – raga Aug 21 '20 at 04:26
  • Actually......no, there's no exp_id in the document. Each sub-document is generated with an _id by mongoDB, so I only pass the exp_id which is just the name of a parameter(not a field of the sub-document) that matches with the _id of the sub-doc. Did I explain myself? lol – Kirasiris Aug 21 '20 at 04:32
  • @ippi i will try that tomorrow morning to see if that works. Its already late now. – Kirasiris Aug 21 '20 at 04:32

1 Answers1

0

Yes you can, using {} searches in all parent documents.

parent.updateMany({}, {$pull, {children: {_id: id}}})

Please also make sure the child _id is a string and not ObjectId. If that's the case you need to first convert your string to ObjectId

garg10may
  • 5,794
  • 11
  • 50
  • 91