简体   繁体   中英

Mongoose - remove array element in update

I have a JSON in this format:

{
   _id:5522ff94a1863450179abd33,
   userName:'bill',
   __v:3,
   friends:[
      {
         _id:55156119ec0b97ec217d8197,
         firstName:'John',
         lastName:'Doe',
         username:'johnDoe'
      },
      {
         _id:5515ce05207842d412c07e03,
         lastName:'Adam',
         firstName:'Foo',
         username:'adamFoo'
      }
   ]
}

And I would like to remove whole corresponding subarray. For example I want to remove user John Doe with ID 55156119ec0b97ec217d8197 so the result will be:

{
   _id:5522ff94a1863450179abd33,
   userName:'bill',
   __v:3,
   friends:[
      {
         _id:5515ce05207842d412c07e03,
         lastName:'Adam',
         firstName:'Foo',
         username:'adamFoo'
      }
   ]
}

So far I have this:

exports.delete = function (req, res) {
    var friends = req.friends[0];

    friends.update(
        {'_id': req.body.friendsId},
        {$pull: {'friends.friends': {_id: req.body.friendId}}}, function (err) {
            if (err) {
                return res.status(400).send({
                    message: getErrorMessage(err)
                });
            } else {
                res.json(friends);
            }
        });
};

But without result and also I'm not getting any error, it will stay just same as before. req.body.friendsId is ID of main array and req.body.friendId is ID of specific user which I want to pull.

Change your update query to this:

exports.delete = function (req, res) {
    var friends = req.friends[0]; // assuming the friends object is your mongodb collection

    friends.update(
        { '_id': req.body.friendsId },
        { $pull: {'friends': { _id: req.body.friendId } } }, function (err) {
            if (err) {
                return res.status(400).send({
                    message: getErrorMessage(err)
                });
            } else {
                res.json(friends);
            }
        });
};

This will search for documents which have the friends array element _id value = req.body.friendsId and removes the specific array element from that array using the $pull operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM