mongo native not creating data

Problem

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 = item.provider.facebook.id;
        console.log("facebook id should be: "+providerId);
        if(providerId == ""){
            collection.update({email:fbEmail, 'provider.facebook.id':""}, {$set: {"provider.facebook.id": fbId}}, {safe:true}, function(err){
                if(err){
                    console.log(err);
                }else{
                    console.log("id updated!");
                };
            });
        }else{ //creates a new user
            console.log("creating a new account...");
            collection.update({'email': fbEmail}, {
                'email': fbEmail,
                'provider':
                    {
                        'facebook': {'id': fbId},                            
                        'twitter': {'id': ""}                                
                    }                    
            }, {upsert:true}, function(err, doc){
                if(err){
                    console.log("Error finding email "+err);
                }                
            });             
        }
    });
});
Problem courtesy of: nihulus

Solution

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

Discussion

There is currently no discussion for this recipe.

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