简体   繁体   中英

Node.JS variable outside function

I am using mongodb and mongoose in node.js Inside the function, it verifies the username and password. user.password works inside the first if statement, but after that in the if else below, where the user actually comes into play it returns.

              if (password1 == user.password) {
                                   ^
TypeError: Cannot read property 'password' of null

The code that I have is.

User.findOne({ 'Username: ': username1}, function(err, user) {
    if (err){
        console.log("There was an error proccesing the request".red + " : ".red + err);
    } else if (user == '') {
        console.log("This user was not found")

    } else {
      prompt('Password: ', function(password1){
          if (password1 == user.password) {

              console.log("User Login Sucsess")
          } else {

              console.log("Password incorrect")
              proccess.exit();
          }


          console.log("made it");


      })

    }
})

Anyone know how to fix this issue

Thank you!

The error message Cannot read property 'password' of null indicates that user is null . But the code is checking for empty string. Check for null instead or in addition. For example, instead of...:

} else if (user == '') {

...do something more like this:

} else if (! user) {

! user ! user will be true if user is empty string or null or any falsy value .

There isn't necessarily anything wrong with the line that's throwing the error:

if (password1 == user.password) {

This is more so where the issue becomes certain. The root of the issue is a few lines up:

} else if (user == '') {
    console.log("This user was not found")

The error message is suggesting that user is null (because null cannot have properties like .password ), meaning in this case that no document was found matching the query. But, the condition isn't catching this, allowing the function to continue to execute beyond it and attempt to read user.password when there isn't a user .

This is because null == '' is false . In JavaScript, the null value is only == to itself or undefined .

var user = null;
console.log(user == '');        // false

console.log(null == '');        // false
console.log(null == null);      // true
console.log(null == undefined); // true

Adjusting the condition to check for null specifically should resolve this:

} else if (user == null) {
    console.log("This user was not found")

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