Search code examples
javascriptnode.jsmongodbexpressnode-mongodb-native

add a condition while inserting data in mongodb


Basicly I want to check if a specific data exists in the database before inserting data(im using native mongodb driver), so what I tried is using collection.findOne() to check if data exists, if the property of the attribute is null the collection.insert() performs.

Apparently my code is not working according the logic, please someone enlighten me!

some of my code:

exports.addUser = function(req, res) {
    var twitterId = req.body.provider;
    var userEmail = req.body.email;

    db.collection('users', function(err, collection) {
        collection.findOne({'email':userEmail }, function(err, item){

            if(item.email === null){

                collection.insert({
                    'email': userEmail,
                    'provider': {
                        'twitter': {
                            'id': twitterId
                        }
                    }
                }, function(err, result) {
                    if (err) {
                        res.send({'error':'An error has occurred'});
                    } else {
                        console.log('Success: ' + JSON.stringify(result[0]));
                        res.send(result[0]);
                    }
                });   

            }else{
                console.log("Email exits ");
            }
        });


    });
}

Solution

  • Your if statement is expecting item.email to be explicitly set to null. If item.email is not a property of item, that if statement will evaluate to false.

    var foo = {bar:'baz'}
    foo.bar // 'baz'
    foo.notSet // undefined
    foo.notSet === undefined // true
    foo.notSet === null // false
    
    // now if we set foo.notSet to undefined...
    foo.notSet = null // undefined
    foo.notSet === null // true
    

    So, there are few options...

    if (item.email) {} else {};
    if ('email' in item) {} else {};
    if (item.hasOwnProperty('email')) {} else {};
    

    If you try and call a property that does not exist on the object itself, JS will check it's prototype, if it doesn't exist on the prototype anywhere, then it will return undefined.

    The in operator will check to see if the left side operand is a property of the right side object.

    Finally Object.hasOwnProperty will check for it's argument as a property on the object.

    All that to say, {upsert:true} would probably be your best bet.