Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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})
  })
);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 });
  }),
);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!