【发布时间】:2017-12-04 22:20:49
【问题描述】:
首先,我想先说我知道还有其他一些与插入/更新(如果不存在)有些相关的帖子;但是,我的情况有点不同,不适合其他帖子。
如果用户的电子邮件不存在,我正在尝试插入新的用户注册记录。我现在正在做的就是插入记录。
一个问题是使用upsert:true 进行重复检查并不能真正起作用,因为在插入记录时会生成所有唯一值,例如JSON Web Token 和Created Date 等。这里是我当前的代码:
MongoClient.connect('mongodb://localhost:27017/norad', function(err, db){
if (err) return router.error( Error(err) );
db.collection('users', function(err, coll){
if (err) return router.error( Error(err) );
coll.insert({
'email' : useremail
,'pass' : userpass
,'total_req': 0
,'threshold_req': 0
,'threshold_start_time': 0
,'ak' : activation_key
,'activated': false
,'adm' : false
,'iat' : iat
,'created' : iat
,'modified' : iat
}
,function(err, writeResults){
console.log( writeResults );
if ( err && err.code == 11000 ) return router.error( ErrorHandler('User already exists.', 'Conflict', 409) )
if ( err ) return router.error( Error(err) );
var r = {'email': writeResults.ops[0].email
,'Response':'Your activation code has been emailed to the address used in registration. Please check your email and follow the instructions for account activation.'
}
,scallback = function(){ return router.submit(r) }
// send the activation email to the user
,res = ActivationEmail(activation_key, useremail, scallback, router)
;
if ( res instanceof Error ) router.error( Error(err) );
}
);
});
});
我没有从中得到任何错误。相反,这可以正常工作并在每次调用时插入一条新记录,即使用户的电子邮件已经存在于表中。
我正在尝试添加功能以检查用户的电子邮件是否已经存在于表中,如果存在则抛出错误,否则,创建一条新记录。
【问题讨论】:
-
也发布错误。
-
在
users.email上创建唯一索引。 -
@AlexBlex 你能用这个解决方案创建一个答案来展示它的外观吗?
标签: node.js mongodb duplicates