[英]Create new document if username or email doesn't exists in MongoDB
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
.我希望username
出现在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!!我已经尝试解决这个问题,但没有成功,但问题恰恰出在$or
查询运算符中,我不知道它为什么会改变我的架构!!
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非常感谢任何信息,谢谢
To keep my documents organized, First I find the document that match my criteria with findOne()
method after I call inside it an insertOne
method :为了使我的文档井井有条,首先,在我在其中调用insertOne
方法后,我使用findOne()
方法找到符合我的条件的文档:
db.collection('users').findOne({$or:[{username:newUserObject.username},{email:newUserObject.email}]},
function(err, doc){
assert.equal(err, null);
let response = { sucess: true, msg: "The User Created Successfully"};
//The User doesn't exist => Add New User
if(!doc){
db.collection('users').insertOne(newUserObject, function(err, res){
if(err){
response.sucess=false;
response.status=500;
response.msg="There was a problem registering the user.";
}
callback(response);
client.close();
});
}
else{
response.msg="The User/Email is Already Exists";
callback(response);
client.close();
}
});
Result结果
I'm not sure that my code is clean and follows a good practice, but it's a good solution for now.我不确定我的代码是否干净并且遵循了良好的实践,但现在它是一个很好的解决方案。
在其他条件下,请仅更新
!res.upserted
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.