How to deal with async. findOrCreate method for passport and mongoose How to deal with async. findOrCreate method for passport and mongoose mongoose mongoose

How to deal with async. findOrCreate method for passport and mongoose


User.find returns an array of documents that match your conditions. In your case you want to use User.findOne instead, and then check if (olduser)... to determine if a matching doc was found.


Hate to nitpick, but the other methods mentioned here break if two users try to signup at the same time-- before you go into production, you'll want to have a look into transactions: http://www.mongodb.org/display/DOCS/two-phase+commit


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