简体   繁体   中英

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

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 });
  }
};

try using

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM