【问题标题】:MongoDB & NodeJS Insert If Not Exists Else Throw ErrorMongoDB和NodeJS插入如果不存在否则抛出错误
【发布时间】:2017-12-04 22:20:49
【问题描述】:

首先,我想先说我知道还有其他一些与插入/更新(如果不存在)有些相关的帖子;但是,我的情况有点不同,不适合其他帖子。

如果用户的电子邮件不存在,我正在尝试插入新的用户注册记录。我现在正在做的就是插入记录。

一个问题是使用upsert:true 进行重复检查并不能真正起作用,因为在插入记录时会生成所有唯一值,例如JSON Web TokenCreated 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


【解决方案1】:

您需要在email 字段上创建unique index。例如。在 mongo shell 中:

db.users.createIndex(
   { email: 1},
   { unique: true } 
);

【讨论】:

  • Alex,我按照你的建议做了,11000 错误代码现在在重复电子邮件输入时成功抛出。这解决了我的问题。谢谢
猜你喜欢
  • 2015-12-02
  • 2012-10-12
  • 2018-10-12
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 2012-03-28
  • 2018-09-17
相关资源
最近更新 更多