2

I try to delete ObjectID in array of ObjectId.

My model:

let directoryCollection = new Schema(
  {
    email: { type: String },
    directory: [{
        name: { type: String },
        list: [ {type: Schema.ObjectId} ]
    }]
  },
  {collection: 'directory'}
);

I have a array of ObjectID in list.

My code for delete index in my array:

let id = mongoose.Types.ObjectId(req.body.id);

directoryModel.update({'email': email, 'directory.name': oldDirectory}, {$pull: {'directory.list': id} }, function (req, result) {
    console.log(result);
    res.json('ok');
 });

But the result is:

{ ok: 0, n: 0, nModified: 0 }

Email variable and oldDirectory variable ara correct. My ID is: 5b5e5f34cfcd3906c8e6aa20

Same in my database:

enter image description here

What is the problem ? Thanks you !

0

1 Answer 1

2

Try this, Correct syntax to $pull from array of objects

directoryModel.update(
  { "email": email, "directory": { "$elemMatch": { "name": oldDirectory } } },
  { "$pull": { "directory.$.list": id } }
})
Sign up to request clarification or add additional context in comments.

1 Comment

This would not work. It would pull the entire directory instead of the element in the array. He already tried this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.