Home > Mobile >  Cannot read properties of undefined (reading '_id') while reading user from backend nodejs
Cannot read properties of undefined (reading '_id') while reading user from backend nodejs

Time:09-22

I am getting the following error in nodejs and expressjs, the code is given below

module.exports.forgotPassword = async (req, res) => {
  try {
    const email = req.body.email;
    const user = await User.findOne({ email: email });
    console.log(user);
    if (user === null) throw new Error("Please register first");
    if (user !== null) {
      const id = user[0]._id.toHexString();
      const token = crypto.randomBytes(64).toString("hex");
      let link = `${id}/${token}`;
      res.status(200).send(link);
    }
  } catch (err) {
    res.status(401).send({ error: err.message });
  }
};

CodePudding user response:

try using

if (user === undefined) throw new Error("Please register first");

CodePudding user response:

The mongo findOne command returns only one single document it does not returns an array . so you can access the id like

const id = user._id.toHexString();

  • Related