Home > Software design >  Updating sub document using save() method in mongoose does not get saved in database and shows no er
Updating sub document using save() method in mongoose does not get saved in database and shows no er

Time:03-31

I have a Mongoose model like this:

const centerSchema = mongoose.Schema({
  centerName: {
    type: String,
    required: true,
  },
  candidates: [
    {
      candidateName: String,
      voteReceived: {
        type: Number,
        default: 0,
      },
      candidateQR: {
        type: String,
        default: null,
      },
    },
  ],
  totalVote: {
    type: Number,
    default: 0,
  },
  centerQR: String,
});

I have a Node.JS controller function like this:

exports.createCenter = async (req, res, next) => {
  const newCenter = await Center.create(req.body);

  newCenter.candidates.forEach(async (candidate, i) => {
    const candidateQRGen = await promisify(qrCode.toDataURL)(
      candidate._id.toString()
    );
    candidate.candidateQR = candidateQRGen;

    // ** Tried these: **
    // newCenter.markModified("candidates."   i);
    // candidate.markModified("candidateQR");
  });

  // * Also tried this *
  // newCenter.markModified("candidates");
  const upDatedCenter = await newCenter.save();
  res.status(201).json(upDatedCenter);
};

Simply, I want to modify the candidateQR field on the subdocument. The result should be like this:

{
    "centerName": "Omuk Center",
    "candidates": [
        {
            "candidateName": "A",
            "voteReceived": 0,
            "candidateQR": "some random qr code text",
            "_id": "624433fc5bd40f70a4fda276"
        },
        {
            "candidateName": "B",
            "voteReceived": 0,
            "candidateQR": "some random qr code text",
            "_id": "624433fc5bd40f70a4fda277"
        },
        {
            "candidateName": "C",
            "voteReceived": 0,
            "candidateQR": "some random qr code text",
            "_id": "624433fc5bd40f70a4fda278"
        }
    ],
    "totalVote": 0,
    "_id": "624433fc5bd40f70a4fda275",
    "__v": 1,
}

But I am getting the candidateQR still as null in the Database. I tried markModified() method. But that didn't help (showed in the comment section in the code above). I didn't get any error message. In response I get the expected result. But that result is not being saved on the database. I just want candidateQR field to be changed. But couldn't figure out how.

CodePudding user response:

As far as I understand, you are just looping through the candidates array but you are not storing the updated array. You need to store the updated data in a variable as well. Please give it a try with the solution below using map.

exports.createCenter = async (req, res, next) => {
  const newCenter = await Center.create(req.body);

  let candidates = newCenter.candidates;
  
  candidates = candidates.map(candidate => {
      const candidateQRGen = await promisify(qrCode.toDataURL)(
          candidate._id.toString()
      );

      return {
          ...candidate,
          candidateQR: candidateQRGen  
      }
  });

  newCenter.candidates = candidates;

  const upDatedCenter = await newCenter.save();

  res.status(201).json(upDatedCenter);
};

CodePudding user response:

You can use this before save()

newCenter.markModified('candidates');
  • Related