简体   繁体   中英

Node.js async try/catch error when getting data from mongoose

I'm trying to make a very basic login page that has three routes LOGIN , REGISTER , and WELCOME . The idea being that you can register a user with a name , email , and password of your choice at which point you will be redirected to login where you can use your information created before entering into the welcome page.

Up until now, I've been saving the user information to an empty array as an object and then searching through it with passport-config to test the credentials. Obviously, this is not secure and also has no way of saving information after a restart of the server. To solve this, I started integrated mongoose into my project. It was working ok, but now, when trying to retrieve my user list in order to check it against the information passed by the user, I am getting the following error:

ReferenceError: Cannot access 'user' before initialization

this is really confusing for me because my code:

try {
  const user = await User.find(new RegExp(user.userEmail, 'i'))
  console.log(user)
  if (user == null) {
    return done(null, false, { message: "No User With That Email" })
  }
  try {
    console.log(password, user.userPassword)
    if (await bcrypt.compare(password, user.userPassword, function (e) { })) {
      return done(null, user)
    } else {
      return done(null, false, { message: "Password Incorrect" })
    }
  } catch (e) {
    return done(e)
  }
} catch (e) {
  return done(e)
}

is wrapped in a try/catch statement. There is also the bcrypt part which you can ignore, it's just for reference.

Firstly, why is my try/catch still throwing an error, and secondly, why am I getting the initialization error?

Thank you, I appreciate your replies.

The problem looks like it's in this line of code

const user = await User.find(new RegExp(user.userEmail, 'i'))

In this line you're trying to access user.userEmail property when you haven't event initialized the user variable yet (you're initializing it in this code line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM