updating related relations in database

  1. i have created groups , which has members , each member has a group array displaying which they are part of . if i delete a group i want that user’s group array also updates. i am using express and mongodb for my project here is my code:

  2. group controller

    const Group = require("../models/Group");
    const User = require("../models/User");
    
    const createGroup = async (req, res) => {
      try {
        const { name, members } = req.body;
        const adminId = req.user.userId;
    
        // Get admin details
        const admin = await User.findById(adminId);
    
        // Process members array
        const groupMembers = await Promise.all(
          members.map(async (member) => {
            if (member.email) {
              const user = await User.findOne({ email: member.email });
              if (user) {
                return { user: user._id, name: user.name, email: user.email };
              }
            }
            return { name: member.name, email: member.email };
          })
        );
    
        // Add admin as the first member
        groupMembers.unshift({
          user: admin._id,
          name: admin.name,
          email: admin.email,
        });
    
        const group = new Group({
          name,
          admin: adminId,
          members: groupMembers,
        });
    
        await group.save();
    
    
        // **Update each member's groups array**
        for (const member of groupMembers) {
          if (member.user) {
            const user = await User.findById(member.user);
            user.groups.push(group._id);
            await user.save();
          }
        }
        res.status(201).json({ message: "Group created successfully", group });
      } catch (error) {
        console.error("Error creating group:", error);
        res.status(500).json({ error: "Failed to create group" });
      }
    };
    
    const addMember = async (req, res) => {
      try {
        const { groupId, member } = req.body;
        const userId = req.user.userId;
    
        const group = await Group.findById(groupId);
        if (!group) {
          return res.status(404).json({ error: "Group not found" });
        }
    
        if (group.admin.toString() !== userId) {
          return res
            .status(403)
            .json({ error: "Only the group admin can add members" });
        }
    
        const newMember = member.email
          ? await User.findOne({ email: member.email })
          : null;
    
        group.members.push(
          newMember
            ? { user: newMember._id, name: newMember.name, email: newMember.email }
            : { name: member.name, email: member.email }
        );
        // **Update the new member's groups array**
        await group.save();
        if (newMember) {
          newMember.groups.push(group._id);
          await newMember.save();
        }
    
        res.status(200).json({ message: "Member added successfully", group });
      } catch (error) {
        console.error("Error adding member:", error);
        res.status(500).json({ error: "Failed to add member" });
      }
    };
    
    const removeMember = async (req, res) => {
      try {
        const { groupId, memberId } = req.body;
        const userId = req.user.userId;
    
        const group = await Group.findById(groupId);
        if (!group) {
          return res.status(404).json({ error: "Group not found" });
        }
    
        if (group.admin.toString() !== userId) {
          return res
            .status(403)
            .json({ error: "Only the group admin can remove members" });
        }
    
        group.members = group.members.filter(
          (member) => member._id.toString() !== memberId
        );
        await group.save();
        // **Update the member's groups array**
        const member = await User.findById(memberId);
        if (member) {
          member.groups = member.groups.filter(
            (group) => group.toString() !== groupId
          );
          await member.save();
        }
    
        res.status(200).json({ message: "Member removed successfully", group });
      } catch (error) {
        console.error("Error removing member:", error);
        res.status(500).json({ error: "Failed to remove member" });
      }
    };
    
    const leaveGroup = async (req, res) => {
      try {
        const { groupId } = req.body;
        const userId = req.user.userId;
    
        const group = await Group.findById(groupId);
        if (!group) {
          return res.status(404).json({ error: "Group not found" });
        }
    
        // If the admin is leaving
        if (group.admin.toString() === userId) {
          // Transfer admin rights to the next member
          const nextAdmin = group.members.find(
            (member) => member.user && member.user.toString() !== userId
          );
          if (!nextAdmin) {
            return res
              .status(400)
              .json({
                error: "Cannot leave the group without transferring admin rights",
              });
          }
          group.admin = nextAdmin.user;
        }
    
        // Remove the member from the group
        group.members = group.members.filter((member) =>
          member.user ? member.user.toString() !== userId : true
        );
        await group.save();
        // **Update the user's groups array**
        const user = await User.findById(userId);
        user.groups = user.groups.filter((group) => group.toString() !== groupId);
        await user.save();
    
        res.status(200).json({ message: "Left group successfully", group });
      } catch (error) {
        console.error("Error leaving group:", error);
        res.status(500).json({ error: "Failed to leave group" });
      }
    };
    
    const editGroup = async (req, res) => {
      try {
        const { groupId, name } = req.body;
        const userId = req.user.userId;
    
        const group = await Group.findById(groupId);
        if (!group) {
          return res.status(404).json({ error: "Group not found" });
        }
    
        if (group.admin.toString() !== userId) {
          return res
            .status(403)
            .json({ error: "Only the group admin can edit group details" });
        }
    
        group.name = name;
        await group.save();
    
        res
          .status(200)
          .json({ message: "Group details updated successfully", group });
      } catch (error) {
        console.error("Error editing group:", error);
        res.status(500).json({ error: "Failed to edit group" });
      }
    };
    
    const addFriendstoGroup = async (req, res) => {
      try {
        const { groupId, friendId } = req.body;
        const userId = req.user.userId;
    
        const group = await Group.findById(groupId);
        if (!group) {
          return res.status(404).json({ error: "Group not found" });
        }
    
        if (group.admin.toString() !== userId) {
          return res
            .status(403)
            .json({ error: "Only the group admin can add members" });
        }
        const friend = await User.findById(friendId);
        if (!friend) {
          return res.status(404).json({ error: "Friend not found" });
        }
    
        const isAlreadyMember = group.members.some(
          (member) => member.user && member.user.toString() == friendId
        );
        if (isAlreadyMember) {
          res.status(404).json({ error: "Friend is already a member of group" });
        }
    
        group.members.push({
          user: friend._id,
          name: friend.name,
          email: friend.email,
        });
        await group.save();
        // **Update the friend's groups array**
        friend.groups.push(group._id);
        await friend.save();
        res
          .status(201)
          .json({ message: "Friend added to group successfully", group });
      } catch (error) {
        console.error("Error adding friend to group:", error);
        res.status(500).json({ error: "Failed to add friend to group" });
      }
    };
    
    module.exports = {
      createGroup,
      addMember,
      removeMember,
      leaveGroup,
      editGroup,
      addFriendstoGroup,
    };
    
    
  3. my user model :

    const mongoose = require("mongoose");
    const bcrypt = require("bcrypt");
    
    const userSchema = new mongoose.Schema({
      name: {
        type: String,
        required: true,
      },
      email: {
        type: String,
        required: true,
        unique: true,
      },
      password: {
        type: String,
        required: true,
      },
      friends: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User",
        },
      ],
      groups: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Group",
        },
      ],
      createdAt: {
        type: Date,
        default: Date.now,
      },
    });
    
    userSchema.pre("save", async function (next) {
      if (this.isModified("password") || this.isNew) {
        this.password = await bcrypt.hash(this.password, 10);
      }
      next();
    });
    
    module.exports = mongoose.model("User", userSchema, "User");
    
    

i deleted a record from database and i was expecting that it would update the arrays

New contributor

Pakshal Shah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật