mongo native not creating data


Im trying to create data if a facebook id exists in the database else create new data, however the first condition works fine but when its creating data nothing happens, ony get connot read property 'provider' of null even i hard code a provider value.

db.collection('accounts', function(err, collection){
    collection.findOne({'email': fbEmail}, function(err, item){
        var providerId =;
        console.log("facebook id should be: "+providerId);
        if(providerId == ""){
            collection.update({email:fbEmail, '':""}, {$set: {"": fbId}}, {safe:true}, function(err){
                    console.log("id updated!");
        }else{ //creates a new user
            console.log("creating a new account...");
            collection.update({'email': fbEmail}, {
                'email': fbEmail,
                        'facebook': {'id': fbId},                            
                        'twitter': {'id': ""}                                
            }, {upsert:true}, function(err, doc){
                    console.log("Error finding email "+err);
Problem courtesy of: nihulus


One (the first one) of accounts collection documents has provider=null. You can modify findOne condition the following way to avoid it:

collection.findOne({'email': fbEmail, 'provider': {$exists: true}}, ...

Note, that this modification will just skip all accounts without provider field set (or with set to null).

Solution courtesy of: Vladimir


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.