Home > Back-end >  Mongoose static method call doesn't work, console logging it does
Mongoose static method call doesn't work, console logging it does

Time:02-24

I'm creating an authentication system using Node and Mongoose. I have a login user function here:

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 });
  }
};

I always get a 400 error. Console logging 'user' shows nothing. When I substitute my 'findByCredentials' function for the commented out 'findById', the code works perfectly. Also, where I console log 'await User.findByCredentials(email, password)' the user I want is console logged, which makes me think the findByCredentials code is implemented correctly.

Here is the code for that:

// 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;

Not exactly sure what I'm doing wrong. Thank you

CodePudding user response:

There's a typo in your code (in second line)

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

findByCredentials not findbyCredentials. See the capital B

  • Related