我已将this tutorial中的身份验证代码合并到我的应用程序中,一切正常。现在我要回去使数据库错误处理更加健壮。在下面的代码中(来自教程),如果他们遇到throw
的问题,他们为什么会save()
出错?有理由不优雅地处理吗?也许是这样的事情:
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);
});
}
});
});
}));
答案 0 :(得分:1)
解决方案很简单:
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来缩短您的代码