skip to Main Content

I have a newGroups array which is an array of group objects. This array contains an id field alongside the actual mongoDB objectID. Projects contain a field called "assignedGroups" which is basically an array of group objects as well. My function should take all the new groups the user has selected and append that to the existing "assignedGroups" array for the selected project. id is a required field for a group. However, when I try to append the newGroups array to the "assignedGroups" array, the ID field somehow gets lost and I have no idea why this happens.

//add a group to a project given the client id and project id
router.post("/add_group", jwtVerify(['Admin', 'Manager']), expressAsyncHandler(
    async (req, res) => {
        console.log('req body: ', req.body);
        const clientId = req.body.clientId;
        const projectId = req.body.projectId;
        const newGroups: group = req.body.newGroups;

        try{
            console.log("received client id: ", clientId);
            const client = await ClientModel.findOne({ id: clientId });


            if(client) {
                const project = client.projects.find((project) => {
                    return project.id == projectId;
                });

                if(project) {
                    console.log("group is: ", newGroups);
                    project.assignedGroups?.push(...newGroups);
                    console.log('new project: ', project);
                    await client.save();

                    res.status(201).send(project);
                } else {
                    res.status(404).send("Project not found");
                }
    
            } else {
                res.status(404).send("Client not found")
            }

        } catch (error) {
            console.log('error is: ', error);
            res.status(500).send("Internal server error adding group to clients project");
        }
    } 
));

I receive the following error in addition to this:
error is: Error: client validation failed: projects.0.assignedGroups.2.id: Path `id` is required.

I have tried printing console logs everywhere and have determined the line responsible for causing the error. It happens specifically when I try to push the newGroups onto the assignedGroups but I have no idea why the data changes. This is the result of my console log for the following lines of code:

   console.log("group is: ", newGroups);
   project.assignedGroups?.push(...newGroups);
   console.log('new project: ', project);

   //OUTPUT
group is:  [
  {
    _id: '6515880ccbb4d907d4aee87b',
    id: '1',
    groupName: 'Frontend',
    backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1688755927/ayajgq9sgud81qzc.jpg',
    people: [
      '64b15aa72b77e4a923cafdc8',
      '64b159e72b77e4a923cafda6',
      '64b3c70fb49306cf1b0b6ff2',
      '64b42de378a9f73779d70d66',
      '64b432fd2512db8f87d31e75',
      '64b43ea14a3e267132a5f292',
      '6515867b44e85bf4fb3a6ddd',
      '65159861578f8e1bf619aea1',
      '65159c216ae2377b2ef80ff4',
      '6515a4986ae2377b2ef8101e',
      '64b159c52b77e4a923cafd9e',
      '65161f64c8530d9744568efd',
      '6536ebca578f8e1bf619d65d'
    ],
    tickets: [
      '1',  '2',  '3',  '4',  '5',  '6',  '7',
      '8',  '9',  '10', '11', '12', '13', '15',
      '16', '17', '18', '20', '21', '22', '23',
      '24', '25', '26', '27', '28', '29', '30',
      '31', '32', '33', '34', '35', '36', '37',
      '47', '53', '54', '55', '56', '57', '58',
      '59', '60', '62', '65', '67', '68', '71'
    ],
    __v: 1
  }
]

new project:  {
  id: '8',
  name: 'Org',
  logo: '../../assets/project-logos/notebook.png',
  color: 'pink-cl',
  assignedGroups: [
    {
      id: '2',
      groupName: 'Integration',
      backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1695910934/ayajgq9sgud81qzc.jpg',
      people: [Array],
      tickets: [Array],
      _id: new ObjectId("65158c173c0c30898fb9aa32"),
      __v: 0
    },
    {
      groupName: 'Security',
      backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1695911006/ayajgq9sgud81qzc.jpg',
      people: [Array],
      tickets: [],
      _id: new ObjectId("65158c5f3c0c30898fb9aa4f"),
      __v: 0,
      id: '4'
    },
    {
      groupName: 'Frontend',
      backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1688755927/ayajgq9sgud81qzc.jpg',
      people: [Array],
      tickets: [Array],
      _id: new ObjectId("6515880ccbb4d907d4aee87b"),
      __v: 1
    }
  ],
  _id: new ObjectId("6515a50078d33c3995f980b9"),
  highPriorityTime: '1h',
  lowPriorityTime: '1w',
  mediumPriorityTime: '1d'
}

As you can see, the Frontend project which is the one that was supposed to be appended indeed does not contain the ID field however, when printing the newGroup, it’s there. Any help would be immensely appreciated.

//EDIT
I have now also tried a slightly different approach with seemingly no progress:

if(client) {
                const project = client.projects.find((project) => {
                    return project.id == projectId;
                });

                if(project) {
                    console.log("groups are: ", newGroups);
                    for (const newGroup of newGroups) {
                        const newGroupWithId = { ...newGroup, id: newGroup.id };
                        console.log("newGroupWithId is: ", newGroupWithId);
                        project.assignedGroups?.push(newGroupWithId);

                        if (project.assignedGroups && project.assignedGroups.length > 0) {
                            const lastGroup = project.assignedGroups[project.assignedGroups.length - 1];
                            console.log('last group: ', lastGroup);
                            if (!lastGroup.id) {
                                lastGroup.id = newGroupWithId.id;
                                console.log('last group in assignedGroups after id update: ', lastGroup);
                            }
                        }
                      }
                    console.log('new project: ', project);
                    await client.save();

                    res.status(201).send(project);
                } else {
                    res.status(404).send("Project not found");
                }
    
            }

Over here, I try a very manual way to first make sure the id does exist for the group when I’m pushing it to the assignedGroups. I even check if the last group in assignedGroups does not contain the id, then I add the id. The code enters the final if block:
if (!lastGroup.id) but still does not update the last group in the assignedGroups array with the id I want! Here is the output:

newGroupWithId:  {
  _id: '6515880ccbb4d907d4aee87b',
  id: '1',
  groupName: 'Frontend',
  backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1688755927/ayajgqes9sguidd81qzc.jpg',
  people: [
    '64b15aa72b77e4a923cafdc8',
    '64b159e72b77e4a923cafda6',
    '64b3c70fb49306cf1b0b6ff2',
    '64b42de378a9f73779d70d66',
    '64b432fd2512db8f87d31e75',
    '64b43ea14a3e267132a5f292',
    '6515867b44e85bf4fb3a6ddd',
    '65159861578f8e1bf619aea1',
    '65159c216ae2377b2ef80ff4',
    '6515a4986ae2377b2ef8101e',
    '64b159c52b77e4a923cafd9e',
    '65161f64c8530d9744568efd',
    '6536ebca578f8e1bf619d65d'
  ],
  tickets: [
    '1',  '2',  '3',  '4',  '5',  '6',  '7',
    '8',  '9',  '10', '11', '12', '13', '15',
    '16', '17', '18', '20', '21', '22', '23',
    '24', '25', '26', '27', '28', '29', '30',
    '31', '32', '33', '34', '35', '36', '37',
    '47', '53', '54', '55', '56', '57', '58',
    '59', '60', '62', '65', '67', '68', '71'
  ],
  __v: 1
}
last group:  {
  groupName: 'Frontend',
  backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1688755927/ayajgqes9sguidd81qzc.jpg',
  people: [
    new ObjectId("64b15aa72b77e4a923cafdc8"),
    new ObjectId("64b159e72b77e4a923cafda6"),
    new ObjectId("64b3c70fb49306cf1b0b6ff2"),
    new ObjectId("64b42de378a9f73779d70d66"),
    new ObjectId("64b432fd2512db8f87d31e75"),
    new ObjectId("64b43ea14a3e267132a5f292"),
    new ObjectId("6515867b44e85bf4fb3a6ddd"),
    new ObjectId("65159861578f8e1bf619aea1"),
    new ObjectId("65159c216ae2377b2ef80ff4"),
    new ObjectId("6515a4986ae2377b2ef8101e"),
    new ObjectId("64b159c52b77e4a923cafd9e"),
    new ObjectId("65161f64c8530d9744568efd"),
    new ObjectId("6536ebca578f8e1bf619d65d")
  ],
  tickets: [
    '1',  '2',  '3',  '4',  '5',  '6',  '7',
    '8',  '9',  '10', '11', '12', '13', '15',
    '16', '17', '18', '20', '21', '22', '23',
    '24', '25', '26', '27', '28', '29', '30',
    '31', '32', '33', '34', '35', '36', '37',
    '47', '53', '54', '55', '56', '57', '58',
    '59', '60', '62', '65', '67', '68', '71'
  ],
  _id: new ObjectId("6515880ccbb4d907d4aee87b"),
  __v: 1
}
last group in assignedGroups after id update:  {
  groupName: 'Frontend',
  backgroundPhoto: 'https://res.cloudinary.com/ds2qotysb/image/upload/v1688755927/ayajgqes9sguidd81qzc.jpg',
  people: [
    new ObjectId("64b15aa72b77e4a923cafdc8"),
    new ObjectId("64b159e72b77e4a923cafda6"),
    new ObjectId("64b3c70fb49306cf1b0b6ff2"),
    new ObjectId("64b42de378a9f73779d70d66"),
    new ObjectId("64b432fd2512db8f87d31e75"),
    new ObjectId("64b43ea14a3e267132a5f292"),
    new ObjectId("6515867b44e85bf4fb3a6ddd"),
    new ObjectId("65159861578f8e1bf619aea1"),
    new ObjectId("65159c216ae2377b2ef80ff4"),
    new ObjectId("6515a4986ae2377b2ef8101e"),
    new ObjectId("64b159c52b77e4a923cafd9e"),
    new ObjectId("65161f64c8530d9744568efd"),
    new ObjectId("6536ebca578f8e1bf619d65d")
  ],
  tickets: [
    '1',  '2',  '3',  '4',  '5',  '6',  '7',
    '8',  '9',  '10', '11', '12', '13', '15',
    '16', '17', '18', '20', '21', '22', '23',
    '24', '25', '26', '27', '28', '29', '30',
    '31', '32', '33', '34', '35', '36', '37',
    '47', '53', '54', '55', '56', '57', '58',
    '59', '60', '62', '65', '67', '68', '71'
  ],
  _id: new ObjectId("6515880ccbb4d907d4aee87b"),
  __v: 1
}

2

Answers


  1. To fix this, you need to copy the ID field to the new embedded document object before you push it to the assignedGroups array. You can do this using the following code:

    const project = client.projects.find((project) => {
      return project.id == projectId;
    });
    
    if (project) {
      console.log("group is: ", newGroups);
    
      // Copy the ID field to each new embedded document object.
      for (const newGroup of newGroups) {
        const newGroupWithId = { ...newGroup, id: newGroup._id };
        project.assignedGroups?.push(newGroupWithId);
      }
    
      console.log("new project: ", project);
      await client.save();
    
      res.status(201).send(project);
    } else {
      res.status(404).send("Project not found");
    }
    
    Login or Signup to reply.
  2. update the schema for your group model:

    const groupSchema = new mongoose.Schema({
      groupName: { type: String, required: true },
      backgroundPhoto: { type: String },
      people: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
      tickets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Ticket" }],
      id: { type: String, required: true },
    });
    
    const Group = mongoose.model("Group", groupSchema);
    

    migrate your existing group data to the new schema

    Group.updateMany({}, { $set: { id: mongoose.Types.ObjectId() } });
    

    push the newGroups array to the assignedGroups array:

    const project = client.projects.find((project) => {
      return project.id == projectId;
    });
    
    if (project) {
      for (const newGroup of newGroups) {
        project.assignedGroups?.push(newGroup);
      }
    
      await client.save();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search