2013-01-21 201 views
1

基本上我想在插入数据之前检查数据库中是否存在特定数据(使用本机mongodb驱动程序),所以我试图使用collection.findOne()来检查数据是否存在,如果collection.insert()执行的属性属性为null。在mongodb中插入数据时添加条件

显然我的代码不是按照逻辑工作的,请有人赐教!

我的一些代码:

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


    }); 
} 
+0

我想我有一个线索,upsert可能是解决它的方法......? – nihulus

+2

正确的,你想要做的是['collection.update'](http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#update)'upsert:true '选项。 – JohnnyHK

回答

1

if声明期待item.email显式地设置为null。如果item.email不是item的财产,那么if语句将评估为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 

因此,有几个选项...

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

如果你试图调用不对象本身上存在的属性,JS会检查它的原型,如果它不存在于原型的任何地方,那么它将返回undefined。

in运算符将检查左侧操作数是否是右侧对象的属性。

最后Object.hasOwnProperty将检查它的参数作为对象的属性。

所有这一切说,{upsert:true}可能是你最好的选择。

+0

是的,我现在在使用upsert,谢谢! – nihulus