First, I'd like to start by saying I know there are several other posts out there somewhat related to inserting/updating if not exists; however, my case is a bit different and doesn't fit other posts.
I'm trying to insert a new user registration record if the user's email doesn't exist. All I'm doing right now is inserting the record.
One problem is that duplication checking with upsert:true doesn't really work because of all the unique values that get generated when a record is going to be inserted like the JSON Web Token, and Created Date, etc. Here is my current code:
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) );
}
);
});
});
I'm not getting any error from this. Instead, this works fine and inserts a new record with every call, even if the user's email is already present in the table.
I'm trying to add functionality to check if the user's email is present in the table already, and throw an error if so, otherwise, create a new record.
users.email.