【问题标题】:Database error handling using Passport and Mongoose使用 Passport 和 Mongoose 处理数据库错误
【发布时间】:2017-02-23 06:33:11
【问题描述】:

我已将来自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);
            });
        }
    });    
    });
}));

【问题讨论】:

    标签: node.js mongodb mongoose passport.js


    【解决方案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 来缩短您的代码

    【讨论】:

    • 是的。我也是这么想的(我刚刚添加了 flash 消息,以便捕捉它并向用户显示错误消息)。
    • 再次感谢。额外问题:process.nextTick() 怎么了?我想我从字面上理解该函数的作用,但为什么我们需要将findOne() 推送到调用堆栈上?它已经包含在一个回调函数中。
    • 在您的代码中,nextTick 无效。下一个刻度的想法是在下一个语句完成后调用包装范围。所以在你的代码中没有下一条语句。阅读此文档:howtonode.org/understanding-process-next-tick 在此文档中您将看到 foo-bar 的示例,它解释了它的作用。
    • 嗯。好的。也许这个故事的寓意是不要相信在线教程中的代码,以至于怀疑我自己的理解。
    • 我阅读/观看教程,但也深入研究包以查看包作者是否有任何其他示例
    猜你喜欢
    • 2017-01-11
    • 2013-03-20
    • 2013-11-30
    • 2012-08-05
    • 2014-01-07
    • 2015-01-24
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多