猫鼬静态方法调用不起作用,控制台记录它

Mongoose static method call doesn't work, console logging it does

我正在使用 Node 和 Mongoose 创建一个身份验证系统。我这里有一个登录用户功能:

export const loginUser = async (req, res) => {
  try {
    const email = req.body.email;
    const password = req.body.password;

    //const workingUser = await User.findById("xxxxxxxxxxxx");
    console.log(await User.findByCredentials(email, password));
    const user = await User.findbyCredentials(email, password);

    console.log(user);

    if (!user) {
      return res.status(401).json({ error: "Login failed! Check authentication credentials." });
    }

    const token = await user.generateAuthToken();

    res.status(201).json({ user, token });

  } catch (error) {
    res.status(400).json({ error: error });
  }
};

我总是收到 400 错误。控制台日志 'user' 什么也没显示。当我用我的 'findByCredentials' 函数替换注释掉的 'findById' 时,代码运行完美。此外,在我控制台日志 'await User.findByCredentials(email, password)' 的地方,我想要的用户是控制台日志记录的,这让我认为 findByCredentials 代码已正确实现。

这是相关代码:

// this method searches for a user by email and password
userSchema.statics.findByCredentials = async (email, password) => {
  console.log(email);
  const user = await User.findOne({ email });

  if (!user) {
    throw new Error({ error: "Invalid login details" });
  }
  const isPasswordMatch = await bcrypt.compare(password, user.password);

  if (!isPasswordMatch) {
    throw new Error({ error: "Invalid login details"});
  }
  return user;
}

const User = mongoose.model("User", userSchema);

export default User;

不太确定我做错了什么。谢谢

您的代码中有错字(第二行)

const user = await User.findByCredentials(email, password);

findByCredentials 不是 findbyCredentials。见首都B