0

I am trying to modify my code (in a passport function) so that it reads values form a mongodb Database instead of from an array.

My initial working code was the following:

  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'})
       }
     }
   )
 )

The modified code (which is identical to the initial one, at the exception of the code which actually fetches the values from the mongodb) is the following (the actual connection to the mongodb is done in a mongoUtil Module - called here - and is working fine):

  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'})
       }
     }
   )
 )

However the user value is not defined outside the block in which it is used. Since I have declared the value before the block within the function, why is it not defined outside the block in question?

user229044
  • 232,980
  • 40
  • 330
  • 338
JF0001
  • 819
  • 7
  • 30
  • "However the user value is not defined outside the block in which it is used" — **function**, not block. – Quentin Jun 07 '20 at 14:31

1 Answers1

1

the user variable outside the mongodb callback is not set because db.collection('Users').findOne({email} returns a promise and the code after the call back will be executed before your call back returns the value

Sven.hig
  • 4,449
  • 2
  • 8
  • 18