Watch keynotes and sessions from, our virtual developer conference.

MongoDB removing subdocument issue

I’m trying to remove specific sub document by it’s _id. In eventArrayModel there are plenty of documents. I’m looking for match for origin of sub document by field resource . This is what i come up with, but it doesn’t work. Any ideas ?

const removedPost = await eventArrayModel.update({resource: req.params.teamMember}, {$pull: { array : {_id: ObjectId("5ef0a884c09b8e9ff01c8007")}}});

The syntax is OK.
But, notice, that ‘req.params.teamMember’ param is of string type, but ‘_id’ that you are trying to match is of type ObjectId. You cannot match ObjectId value with a string. Nothing matched - nothing updated.
You need to convert teamMember to ObjectId to do a successful match:

// Node.js example
const bson = require('bson');
const teamMemberId = new bson.ObjectId(req.params.teamMember);
const removeId = new bsonObjectId(<id>);
await eventArrayModel.update(
  { resource: teamMemberId }, 
     $pull: { 
       array : { _id: removeId }

You can try any of these two update queries:

  { 'array.resource': req.params.teamMember }, 
  { $pull: { array: { _id: ObjectId(...) } } } 

  { }, 
  { $pull: { array: { _id: ObjectId(...), resource: req.params.teamMember } } }