繁体   English   中英

Node.JS变量外函数

[英]Node.JS variable outside function

我在node.js中使用mongodb和mongoose,在函数内部,它验证用户名和密码。 user.password在第一个if语句中起作用,但之后在下面的if else中,用户实际使用的位置将返回。

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

我拥有的代码是。

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


      })

    }
})

任何人都知道如何解决此问题

谢谢!

错误消息Cannot read property 'password' of null表示usernull 但是代码正在检查空字符串。 检查是否为null替代或附加。 例如,代替...:

} else if (user == '') {

...做更多这样的事情:

} else if (! user) {

! user ! user如果将真正的user是空字符串或null或任何falsy值

引发错误的行不一定有任何错误:

if (password1 == user.password) {

在确定问题的地方更是如此。 问题的根源在于几行:

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

错误消息表明usernull (因为null不能具有.password属性),这意味着在这种情况下,找不到与查询匹配的文档。 但是,条件并没有解决这个问题,它允许函数继续执行,并在没有user尝试读取user.password

这是因为null == ''false 在JavaScript中, null值本身==undefined

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

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

调整条件以专门检查是否为null可以解决此问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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