Javascript 在mongodb中插入数据时添加条件
基本上,我想在插入数据之前检查数据库中是否存在特定数据(我使用本机mongodb驱动程序),因此我尝试使用Javascript 在mongodb中插入数据时添加条件,javascript,node.js,mongodb,express,node-mongodb-native,Javascript,Node.js,Mongodb,Express,Node Mongodb Native,基本上,我想在插入数据之前检查数据库中是否存在特定数据(我使用本机mongodb驱动程序),因此我尝试使用collection.findOne()检查数据是否存在,如果属性的属性为null,则执行collection.insert() 显然我的代码没有按照逻辑运行,请有人给我点化一下 我的一些代码: exports.addUser = function(req, res) { var twitterId = req.body.provider; var userEmail = r
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
语句希望项.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
运算符中的将检查左侧操作数是否是右侧对象的属性
最后,Object.hasOwnProperty
将检查它的参数作为对象的属性
所有这些都表明,{upsert:true}
可能是您的最佳选择。如果您的语句期望项。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
运算符中的将检查左侧操作数是否是右侧对象的属性
最后,Object.hasOwnProperty
将检查它的参数作为对象的属性
所有这些都表明,{upsert:true}
可能是你最好的选择。我想我有一个线索,upsert可能是解决它的方法…?对,你想做的是使用upsert:true
选项。我想我有一个线索,upsert可能是解决它的方法…?对,您要做的是使用upsert:true
选项。