Search code examples
node.jsarraysexpressfindoneandupdate

How to add an id to an array of object when pushing a new object into the array in node


I have an array called "previousEducation" which initially was empty array, but once I push an object into the array, I want each object that will be push into the array to have an object id. Although from the screenshot I uploaded, the object id was in both (1) and (2) but I don't need the aspect where I circled in (1) I want something inform of the one I named (2) where each object will be having an id follow by the req.body. Is there a way I can push req.body into the array and archive that.

Note: the key value pair from my req.body which has been destructured to become myBody are: exam: "waec" subject: "english" grade: "a1" yera: "2023" examNo: "com1234" candidateNo: "waec7676" identificationNo: "DE89392982"

Thanks.

My code.

  const {receivedEmail, ...myBody} = req.body 
  studentModel.findOneAndUpdate(
    {email: req.body.receivedEmail},
    {$push: {previousEducation:{ _id: new ObjectId(), myBody}}}
  )
  .then((response) => {
    // console.log(response + 'JWT');
    res.send({message: 'O level Result added successfully', status: true, response});
  })
}```[![The image screenshot][1]][1]


  [1]: https://i.sstatic.net/sztiw.png

Solution

  • Spread your myBody Object. When you are pushing it to the array. Add the spread operator ...myBody like this when pushing it to the array.

    const {receivedEmail, ...myBody} = req.body 
      studentModel.findOneAndUpdate(
        {email: req.body.receivedEmail},
        {$push: {previousEducation:{ _id: new ObjectId(), ...myBody}}}
      )
      .then((response) => {
        // console.log(response + 'JWT');
        res.send({message: 'O level Result added successfully', status: true, response});
      })
    }