使用 Passport 和 Mongoose 处理数据库错误

Database error handling using Passport and Mongoose

我已将 this tutorial 的身份验证代码合并到我的应用程序中,一切正常。现在我要回去使数据库错误处理更健壮。在下面的代码中(来自教程),如果他们用 save() 遇到障碍,为什么他们会 throw 错误?有理由不更优雅地处理吗?也许是这样的:

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

来自教程:

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

解决方法很简单:

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

即使在 mongoose 中 documentation 保存也不会抛出异常。

您正在阅读的解决方案太旧:2013 年 12 月 4 日。为什么不从它的纯来源阅读最新的文档呢?

读这个:http://passportjs.org/docs/configure



奖励:我建议使用插件 mongoose findOrCreate

来缩短您的代码