【问题标题】:Variable not Defined Outside a Specific Block [duplicate]未在特定块之外定义的变量[重复]
【发布时间】:2020-09-26 12:06:42
【问题描述】:

我正在尝试修改我的代码(在护照函数中),以便它从 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'})
       }
     }
   )
 )

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

【问题讨论】:

  • “但是用户值没有在使用它的块之外定义” - 函数,而不是块。

标签: javascript node.js mongodb express passport.js


【解决方案1】:

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

【讨论】:

  • 我明白了。说得通。谢谢 Sven.hig。
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2022-12-31
  • 2014-10-09
相关资源
最近更新 更多