在mongodb中插入数据时添加一个条件

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

显然我的代码不按照逻辑工作,请有人启发我!

我的一些代码:

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

您的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}可能是你最好的select。