You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose自定义实例方法失效:调用checkPassword时报‘不是函数’错误

问题根源与修复方案

核心问题

报错user.checkPassword is not a function的原因是你使用了User.find({ email })——这个方法返回的是匹配查询条件的用户数组,而Mongoose的实例方法(比如你定义的checkPassword)是挂载在单个用户文档对象上的,数组没有该方法,因此触发报错。

修复步骤

  1. 替换查询方法:把User.find改成User.findOne,它会返回单个匹配的用户文档(如果存在),这样就能正常调用实例方法。
  2. 统一错误类型:代码里同时出现了Unauthenticated和UnauthenticatedError,需保持一致,避免抛出未定义的错误。
  3. 保留用户存在性校验:User.findOne未找到匹配用户时会返回null,原代码的if (!user)判断逻辑正确,可直接保留。

修改后的登录控制器代码

exports.login = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    throw new BadRequest("Please provide email or password.");
  }
  // 改用findOne获取单个用户文档
  const user = await User.findOne({ email });
  if (!user) {
    throw new UnauthenticatedError("Invalid Credentials");
  }
  // 现在可正常调用实例方法
  const isPasswordCorrect = await user.checkPassword(password);
  if (!isPasswordCorrect) {
    throw new UnauthenticatedError("Invalid credentials");
  }
  const token = user.createJWT();
  res.status(StatusCodes.CREATED).json({ user: { name: user.name }, token });
};

模型代码确认

你的checkPassword实例方法定义完全正确,无需修改:

userSchema.methods.checkPassword = async function (candidatePassword) {
  let isCorrect = await bcrypt.compare(candidatePassword, this.password);
  return isCorrect;
};

内容的提问来源于stack exchange,提问作者Shantanu Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:52:43