0

I got this document:

{
"_id" : "111",
"email" : "[email protected]",
"username" : "michael098",
"groups" : [
    {
        "_id" : "222"
        "groupName" : "family",
        "groupMembers" : [
            {
                "_id" : "333"
                "name" : "Liam"
            },
            {
                "_id" : "444"
                "name" : "Noah"
            }
        ]
    },
    {
        "_id" : "555"
        "groupName" : "friends",
        "groupMembers" : [
            {
                "_id" : "666"
                "name" : "Oliver"
            }
        ]
    }
  ]
}

I am trying to delete 1 group member by _id, for example if I get userId="111", groupId="222" and groupMemberId="444" the group member with _id="444" will delete.

Example of the document after this delete request:

{
"_id" : "111",
"email" : "[email protected]",
"username" : "michael098",
"groups" : [
    {
        "_id" : "222"
        "groupName" : "family",
        "groupMembers" : [
            {
                "_id" : "333"
                "name" : "Liam"
            }
        ]
    },
    {
        "_id" : "555"
        "groupName" : "friends",
        "groupMembers" : [
            {
                "_id" : "666"
                "name" : "Oliver"
            }
        ]
    }
  ]
}

My attempt (with express and mongoose):

router.delete(
  "/:userId/:groupId/:groupMemberId",
  catchAsync(async (req, res) => {
    const { userId, groupId, groupMemberId } = req.params;
    const updatedUser = await User.findByIdAndUpdate(
      userId,
      { $pull: { "groups.$.groupMembers": { _id: groupMemberId } } },
      { new: true }
    );
    res.send({ updatedUser });
  })
);

The response from this request: I get an error: “The positional operator did not find the match needed from the query.”

3
  • The sample document contains invalid JSON and you refer to a userId key that is not present. Those issues make it difficult to answer the question without making several assumptions. Could you post a valid document with all the required fields? Commented Nov 19, 2021 at 20:36
  • userId is the _id for the user, for example in this document the userId is "111", this is not a new field this is the _id field, I refer it as a userId so it can be understandable. Commented Nov 19, 2021 at 20:46
  • 1
    The all positional operator lets you pull multiple objects from a nested array. Does this Mongo Playground do what you want? Commented Nov 19, 2021 at 23:23

0

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.