0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, problem was in friends object

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.