tcquinn
tcquinn

Reputation: 413

Database error handling using Passport and Mongoose

I've incorporated the authentication code from this tutorial into my application and everything is working. Now I'm going back to make the database error handling more robust. In the code below (from the tutorial), why do they throw the error if they hit a snag with the save()? Is there a reason not to handle more gracefully? Perhaps something like:

if (err)
    return done(err, false, req.flash('signupMessage', 'Encountered database error.'));

From the tutorial:

passport.use('local-signup', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
    // asynchronous
    // User.findOne wont fire unless data is sent back
    process.nextTick(function() {
    // find a user whose email is the same as the forms email
    // we are checking to see if the user trying to login already exists
    User.findOne({ 'local.email' :  email }, function(err, user) {
        // if there are any errors, return the error
        if (err)
            return done(err);
        // check to see if theres already a user with that email
        if (user) {
            return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
        } else {
            // if there is no user with that email
            // create the user
            var newUser            = new User();
            // set the user's local credentials
            newUser.local.email    = email;
            newUser.local.password = newUser.generateHash(password);
            // save the user
            newUser.save(function(err) {
                if (err)
                    throw err;
                return done(null, newUser);
            });
        }
    });    
    });
}));

Upvotes: 0

Views: 200

Answers (1)

num8er
num8er

Reputation: 19372

solution is simple:

newUser.save(function(err) {
  if (err) {
    return done(err);
  }
  return done(null, newUser);
});

even in mongoose documentation saving is done without throwing exception.

solution that You're reading is too old: Dec 04, 2013. Why not to read latest documentation from it's pure source?

Read this: http://passportjs.org/docs/configure



BONUS: I would recommend to shorten Your code by using plugin mongoose findOrCreate

Upvotes: 1

Related Questions