如何处理异步。护照和猫鼬的findOrCreate方法

时间:2012-06-22 11:13:43

标签: node.js authentication express mongoose passport.js

身份验证模块“Passport”需要FindOrCreate方法才能进行登录。我使用mongoose以使用以下架构保存我的用户:

var UserSchema = new Schema({
    firstname: String,
    lastname: String,
    email: String,
    accounts: []
});

accounts数组包含代表facebook帐户的对象,例如{provider: "facebook", uid: "someFacebookId"}

我的身份验证策略如下所示:

// Authentication Strategy
passport.use(new FacebookStrategy({
    clientID: CONFIG.fb.appId,
    clientSecret: CONFIG.fb.appSecret,
    callbackURL: CONFIG.fb.callbackURL
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      User.find({ 'accounts.uid': profile.id, 'accounts.provider': 'facebook' }, function(err, olduser) {

          if(olduser._id) {
            console.log('User: ' + olduser.firstname + ' ' + olduser.lastname + ' found and logged in!');
            done(null, olduser);
          } else {
            var newuser = new User();
            var account = {provider: "facebook", uid: profile.id};
            newuser.accounts.push(account);
            newuser.firstname = profile.name.givenName;
            newuser.lastname = profile.name.familyName;
            newuser.email = "TBD...";

            newuser.save(function(err) {
              if(err) { throw err; }
              console.log('New user: ' + newuser.firstname + ' ' + newuser.lastname + ' created and logged in!');
              done(null, newuser);
            });
          }
        });
    });
  }
));

问题:查询我的数据库(User.find(...))后,立即执行回调函数,而不等待我的数据库回答。这会导致未定义的olduser对象。因此,每次该用户尝试登录时,我都会将同一用户的同意用户添加到我的数据库中。

如何正确处理此异步回调?

4 个答案:

答案 0 :(得分:4)

User.find会返回符合条件的数组文档。在您的情况下,您希望改为使用User.findOne,然后选中if (olduser)...以确定是否找到了匹配的文档。

答案 1 :(得分:3)

讨厌挑剔,但如果两个用户同时尝试注册,那么此处提到的其他方法会中断 - 在投入生产之前,您需要查看交易:http://www.mongodb.org/display/DOCS/two-phase+commit

答案 2 :(得分:1)

process.nextTick(function () {
      var query = User.findOne({ 'fbId': profile.id });
      query.exec(function (err, oldUser) {
        console.log(oldUser);
        if(oldUser) {
          console.log('User: ' + oldUser.name + ' found and logged in!');
          done(null, oldUser);
        } else {
          var newUser = new User();
          newUser.fbId = profile.id;
          newUser.name = profile.displayName;
          newUser.email = profile.emails[0].value;

          newUser.save(function(err) {
            if(err) {throw err;}
            console.log('New user: ' + newUser.name + ' created and logged in!');
            done(null, newUser);
          }); 
        }
      });
    });

答案 3 :(得分:0)

有一个应用程序:mongoose-findorcreate