javascript - 我得到 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)
我检查了拼写,甚至更改了函数名称以查看它是否有效,但不知道为什么会出现此错误。请帮忙
解决方案
问题是您使用的是 find() 方法而不是 findOne()。
find() 返回集合数组而不是对象。尝试这个:
const isMatch = await user[0].checkHashedPassword(password)
推荐阅读
- html - 使用 xslt 从 xml 获取 HTML 列表中的值
- python - 如何在pygame游戏中的角色位置投掷炸弹
- reactjs - react-pdf 提交多个值
- c# - 如何将没有属性的 XML 转换为 C# 属性?
- windows - tasklist 命令是 cpu 重的命令吗?
- c++ - TTF_RenderText_Solid(...) 导致分段错误错误
- intellij-idea - IntelliJ,删除滚动条
- excel - 如何通过 .ODC 文件建立数据库 SSL 连接
- r - 在 R 数据框列中将“A”替换为 1,将“B”替换为 2
- c# - 使用 Include 方法显示联合表中的特定字段