Home > Enterprise >  findByIdAndUpdate sometimes work and other times not
findByIdAndUpdate sometimes work and other times not

Time:01-09

I am trying to update two document in mongoose but I keep getting

UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined"

But sometimes it works. What am I doing wrong?


const Installateurs = require("../../Models/Installateurs.js");
const Opdrachten = require("../../Models/Opdracht.js");

const verzendOpdrachtNaarInstallateur = (req, response) => {

  Opdrachten.findByIdAndUpdate(req.body._id, req.body).then((result) => {
    const id = result.installateurs[0]._id;

    Installateurs.findById(id).then((res) => {
      res.opdrachten.push(result._id);
      res.huidigeOpdracht.push(result._id);

      console.log(res);

      Installateurs.findByIdAndUpdate(id, res, { new: true })
        .then((updatedInstal) => {
          response.json(updatedInstal);
        })
        .catch((err) => console.log(err));
    });
  });
};

module.exports = verzendOpdrachtNaarInstallateur;

CodePudding user response:

not sure but i think its because you have not handled error. Try this

const Installateurs = require("../../Models/Installateurs.js");
const Opdrachten = require("../../Models/Opdracht.js");

const verzendOpdrachtNaarInstallateur = (req, response) => {

  Opdrachten.findByIdAndUpdate(req.body._id, req.body).then((result) => {
    const id = result.installateurs[0]._id;

    Installateurs.findById(id).then((res) => {
      res.opdrachten.push(result._id);
      res.huidigeOpdracht.push(result._id);

      console.log(res);

      Installateurs.findByIdAndUpdate(id, res, { new: true })
        .then((updatedInstal) => {
          response.json(updatedInstal);
        })
        .catch((err) => console.log(err));
    });
  }).catch((err) => console.log(err));
};

module.exports = verzendOpdrachtNaarInstallateur;

CodePudding user response:

From what I can tell from the code, Looks like:

Either Your Opdrachten.findByIdAndUpdate is not returning result.installateurs property

or

Your Installateurs.findById is returning undefined.

As much as I can tell from the context for the code.

  • Related