Home > Mobile >  Remove object from nested array of objects
Remove object from nested array of objects

Time:11-18

I got this user schema

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  groups: [
    {
      groupName: {
        type: String,
        required: true,
      },
      groupMembers: [{ type: Schema.Types.ObjectId, ref: "GroupMember" }],
    },
  ],
});

And I want to delete a group from the ‘groups’ array based on given ‘userId’ and ‘groupId’, my attempt (with express and mongoose):

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

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

CodePudding user response:

Assuming an actual doc might look like this (using strings instead of ObjectId to keep the example tighter):

    {_id:1, groups: [ { type: "ID1", ref: "XX" }, { type: "ID2", ref: "G1" }, { type: \
"ID3", ref: "G2" } ] }

then this update will remove the subdoc in the groups array where _id = 1 and type = ID2:

db.foo.update({_id:1},  
              { $pull: { groups: { type: "ID2" } }}
             );

  • Related