简体   繁体   中英

Delete nested object with mongoose

I got this mongoose schemas:

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


const GroupMemberSchema = new Schema({
    firstName: String,
    lastName: String,
    birthday: Date,
    gender: String,
    age: Number
});

I want to have 2 routes:

  • Delete a group member from the groupMembers array based on objectId.
  • Delete a whole group from the groups array based on objectId.

My attempt for the delete group member route. This route removes the group member from the groupMembers collection succesfully, but the group member still exist in the user collection:

router.delete(
  "/:userId/:groupId/:groupMemberId",
  catchAsync(async (req, res) => {
    const { userId, groupId, groupMemberId } = req.params;
    await GroupMember.findByIdAndDelete(groupMemberId);
    const user = await User.findById(userId);
    const group = user.groups.find((group) => group._id.toString() === groupId);
    const groupIndex = user.groups.indexOf(group);
    const updatedGroupmembers = user.groups[groupIndex].groupMembers.filter(groupMember=> groupMember._id.toString()!==groupMemberId);
    res.send({updatedGroupmembers})
  })
);

Did you try using $pull?

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

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