首页 > 解决方案 > 我得到 TypeError is not a function in nodeJS

问题描述

我有一个登录路线,但每当它给我一个 typeError 而不是一个函数时。我已经检查了太多次代码,但仍然不明白为什么它给了我这个错误:

这是代码:

router.post("/login", async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(400).send("Please provide an email and password");
    }

    const user = await User.find({ email });

    if (!user) return res.status(401).send("User not found");
    const isMatch = await user.checkHashedPassword(password);
    if (!isMatch) return res.status(401).send("Invalid credentials");
    sendTokenResponse(user, 200, res);
  } catch (ex) {
    console.log(ex);
  }
});

我得到的错误是 user.checkHashedPassword 不是函数。

这是 userSchema 中的 checkHashedPassword 方法:

userSchema.methods.checkHashedPassword = async function (enteredPassword) {
  return await bcrypt.compare(enteredPassword, this.password);
};

这是我得到的完整错误:

TypeError: user.checkHashedPassword is not a function
    at D:\pythonprogs\todoapp\routes\users.js:46:32
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

我检查了拼写,甚至更改了函数名称以查看它是否有效,但不知道为什么会出现此错误。请帮忙

标签: javascriptnode.jstypeerror

解决方案


问题是您使用的是 find() 方法而不是 findOne()。

find() 返回集合数组而不是对象。尝试这个:

const isMatch = await user[0].checkHashedPassword(password)

推荐阅读