Javascript 我发现TypeError不是nodeJS中的函数
我有一个登录路径,但每当它给我一个类型错误,而不是一个函数。我已经检查代码太多次了,但仍然无法理解为什么它会给我这个错误: 代码如下:Javascript 我发现TypeError不是nodeJS中的函数,javascript,node.js,typeerror,Javascript,Node.js,Typeerror,我有一个登录路径,但每当它给我一个类型错误,而不是一个函数。我已经检查代码太多次了,但仍然无法理解为什么它会给我这个错误: 代码如下: router.post("/login", async (req, res) => { try { const { email, password } = req.body; if (!email || !password) { return res.status(400).send("Plea
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)
@Adil Khalil这没有意义,因为我正在使用另一个userSchema方法,它可以工作。请注意,userSchema是一个mongoose模式,非常感谢您。这很有效。我之所以使用find,是因为在我的模式中,电子邮件被设置为唯一的,所以db中只能有一封电子邮件。但是,再次谢谢你。你救了我的命day@ohnope . mongo查找行为是返回数组。它不关心结果是一个对象还是一组对象。因此,使用find()方法和find one()方法是有原因的。