首页 > 解决方案 > 未在特定块外定义的变量

问题描述

我正在尝试修改我的代码(在护照函数中),以便它从 mongodb 数据库而不是从数组中读取值。

我最初的工作代码如下:

  passport.use(
   new LocalStrategy(
     {
       usernameField: "email",
       passwordField: "userName"
     },

     (email, variable, done) => {

       let user = users.find((user) => {
         return user.email  === email 
       })

       if (user) {
         done(null, user)
       } else {
         done(null, false, { message: 'Incorrect username or password'})
       }
     }
   )
 )

修改后的代码(与最初的代码相同,除了实际从 mongodb 获取值的代码)如下(与 mongodb 的实际连接是在 mongoUtil 模块中完成的 - 在此处调用 - 并且正在工作美好的):

  passport.use(
   new LocalStrategy(
     {
       usernameField: "email",
       passwordField: "userName"
     },

     (email, variable, done) => {

       var user
       mongoUtil.connectToServer(function(err, client) {
         var db = mongoUtil.getDb()
         db.collection('Users').findOne({email}, function(err, result) {
           user = result
           return user.email === email
         })
       })

       if (user) {
         done(null, user)
       } else {
         done(null, false, { message: 'Incorrect username or password'})
       }
     }
   )
 )

但是,用户值未在使用它的块之外定义。既然我已经在函数内的块之前声明了值,为什么没有在相关块之外定义它?

标签: javascriptnode.jsmongodbexpresspassport.js

解决方案


未设置 mongodb 回调之外的用户变量,因为 db.collection('Users').findOne({email}返回一个承诺,并且回调之后的代码将在您的回调返回值之前执行


推荐阅读