Mongoose deleting (pull) a document within an array, does not work with ObjectID

It seems that the above code would not work. It should not even have worked for the first example I gave.

In the end I was supported by this answer here: MongoDB, remove object from array

Here is my working code:

userAccounts.update( 
    { userId: usr.userId },
    {
        $pull: {
            connections: { _id : connId }
        }
    },
    { safe: true },
    function removeConnectionsCB(err, obj) {
        // ...
    }
);

I have a document like

enter image description here

I have to delete address from address array

After searching lots on internet I found the solution

Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }
    res.json(data);   
});

user: {
 _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
 name: 'Test',
 posts: [
  ObjectId("5cd07ee05c08f51af8d23b64"),
  ObjectId("5cd07ee05c08f51af8d23c52")
 ]
}

Remove a single post from posts array

user.posts.pull("5cd07ee05c08f51af8d23b64"); user.save();


To use update with ObjectId, you should use ObjectId object instead of string representation :

var ObjectId = require('mongoose').Types.ObjectId;

userAccounts.update(
    { 'connections._id': new ObjectId('1234-someId-6789') }, 
    { $pull: { 'connections._id': new ObjectId('1234-someId-6789') } }, 
    function (err,val) {
        console.log(val)
    }
);