38

I have the following mongoose schema:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

I would like to delete the second item in the connections array, to get the following:

user = {
    "userId" : "myId",
    "connections": 
    [{
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

The following code does the job as expected:

userAccounts.update(
    { 'connections.isActive': false }, 
    { $pull: { 'connections.isActive':false }}, 
    function (err, val) {
        console.log(val)
    }
);

But, I need to delete based on ObjectId. And the following goes does not work:

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

Any suggestions? I have been banging my head against the screen (aka Google, Stackoverflow, ...) for hours and have had no luck.

1

9 Answers 9

55

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) {
        // ...
    }
);
2
  • 2
    and connId and usr.userId is an instanceof ObjectId? Mar 6, 2014 at 15:56
  • I thought safe: true was set by default? Dec 21, 2017 at 23:36
22

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);   
});
3
  • Exactly same problem but doesn't work for me. What version of mongodb is this? Jul 5, 2018 at 17:35
  • What was your query and route url ? What if it is dynamic in addressId
    – NoobCoder
    Jun 17, 2019 at 11:19
  • you should do the update query like this Customer.findOneAndUpdate(query, {$pull: {address: mongoose.Type.ObjectId(addressId)}}, (err, data) => { if (err) { return res.status(500).json({ error: 'error in deleting address' }); } res.json(data); }); Jul 11, 2021 at 2:26
11
user: {
 _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
 name: 'Test',
 posts: [
  ObjectId("5cd07ee05c08f51af8d23b64"),
  ObjectId("5cd07ee05c08f51af8d23c52")
 ]
}

Remove a single post from posts array

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

2
  • The best specially if you're updating a found document. Oct 30, 2019 at 17:01
  • same thing didn't work for me, no err, just didn't work, any clue??
    – ezio4df
    Jul 14, 2020 at 15:52
10

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)
    }
);
2
  • Thanks for your answer. Technically, I think you are right. But I was actually referencing my code using the valid ObjectId JSON format. I have posted my own answer.
    – psiphi75
    Nov 28, 2013 at 22:12
  • 2
    I think your code is a little bit misleading. For instance in line 3, you wrote connections_.id when in fact the original question clearly shows that connections is an array of objects with no _id property attached to it.
    – AllJs
    Dec 4, 2016 at 7:32
7

use findByIdAndUpdate to remove an item from an array

You can do it in mongoose 5.4.x and above

const result = await User.findByIdAndUpdate(user_id, {
    $pull: {
        someArrayName: { _id: array_item_id }
    }
}, { new: true });

The item from array will be removed based on provided property _id value

3

If you are using mongoose, no need to use the MongoDB stuff, I mean that's why we're using mongoose in the first place, right?

userAccounts.connections.pull({ _id: '1234-someId-6789'});
await userAccounts.save();
1

mongoose: 4.11.11
What have worked for me is the following syntax:

const removeTansactionFromUser = (userId, connectionId) => {
    return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};

Mongoose support id in string format or ObjectId format.
Tip: new ObjectId(stringId) to switch from string to ObjectId

0
1

In mongoose 5.8.11, this $pull: { ... } didn't work for me, so far not sure why. So I overcame it in my controller this way:

exports.removePost = async (req, res, next) => {
  const postId = req.params.postId;
  try {
    const foundPost = await Post.findById(postId);
    const foundUser = await User.findById(req.userId);
    if (!foundPost || !foundUser) {
      const err = new Error(
        'Could not find post / user.',
      );
      err.statusCode = 404;
      throw err;
    }
    // delete post from posts collection:
    await Post.findByIdAndRemove(postId);
    // also delete that post from posts array of id's in user's collection:
    foundUser.posts.pull({ _id: postId });
    await foundUser.save();
    res.status(200).json({ message: 'Deleted post.' });
  } catch (err) {
    // ...
  }
};
0

Note: If you use the pull method with syntax: $pull: {propertyId: _id} with _id can be found from a document, ensure that _id is string type if not using the method toString() to convert to string type. Let's check it!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.