未加星标

add a condition while inserting data in mongodb

字体大小 | |
[数据库(综合) 所属分类 数据库(综合) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

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

Problem courtesy of: nihulus

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.

Solution courtesy of: Tj Krusinski

本文数据库(综合)相关术语:系统安全软件

代码区博客精选文章
分页:12
转载请注明
本文标题:add a condition while inserting data in mongodb
本站链接:https://www.codesec.net/view/610761.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(综合) | 评论(0) | 阅读(169)