Kim Kim - 3 months ago 71
Node.js Question

Using promises in mongoose for passport authentication

var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');

module.exports = function(passport){
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){

User.findOne({'local.username': email}).exec()
.then(function(user) {
console.log(user);
if(user){
return done(null, false, {message: 'Username already taken!'});
}
else{
var newUser = new User();

newUser.local.username = email;
newUser.local.password = password;

return newUser.save();
}
})
.then(function(user) {
console.log('DEBUG DEBUG DEBUG');
done(null, user);
})
.catch(function(err) {
done(err);
});
}
));

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(userid, done) {
User.findById(userid).exec()
.then(function(user) {
done(user);
});
});
};


In my case the debug log always be printed, whether return
newUser.save()
is called or not.
Is it possible to make the debug log only be printed when return
newUser.save()
is called?

Btw I'm using passportJS for authentication things and for the promise I'm override mongoose default promise with global es6 promise.

Answer

You mean like this? Sorry if there are extra brackets or parenthesis. I edited in the text box. :(

   User.findOne({'local.username': email}).exec()
      .then(function(user) {

        if(user){
          return done(null, false, {message: 'Username already taken!'});
        }
        else{
          var newUser = new User();

          newUser.local.username = email;
          newUser.local.password = password;

          return newUser.save()
              .then(function(){
                  console.log('DEBUG DEBUG DEBUG');              
                  done(null, user);      
              })
        }
      })
      .catch(function(err) {
        done(err);
      });
  }
  ));