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 document if username or email doesn't exists.
My code work fine, the only problem is my schema is not organized as I want. I want that the username
to appear before email
.
Problem
I already try to solve this problem and I did not succeed, but the problem exactly is in $or
query operator, I don't know why it changes my schema!!
Here is my code
//My Schema
let newUserObject = {
username: body.username,
email: body.email,
password: body.password
};
//upsert: true => create doc if username or email doesn't exists
db.collection('users').updateOne(
{$or:[{username:newUserObject.username},{email:newUserObject.email}]},
{ $setOnInsert: newUserObject },
{ upsert: true }, function(err, res) {
let response = { sucess: true, msg: "The User Created Successfully"};
if(err){
response.sucess=false;
response.status=500;
response.msg="There was a problem registering the user.";
}else if(!res.result.upserted)
response.msg="The User/Email is Already Exists";
callback(response);
client.close();
});
Any information is much appreciated, Thanks