简体   繁体   English

如果 MongoDB 中不存在用户名或电子邮件,则创建新文档

[英]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.

相关问题 如果 MongoDB 不存在,如何添加新文档? - How to add new document in MongoDB if it doesn't exists? 如果存在则更新 Many ,否则为每个不存在的 LeadId 创建一个新文档 - Update Many if exists , otherwise create for each LeadId that doesn't exists a new Document 如果文档的 _id 已经存在,如何将数组元素推送到数组,如果 _id 不存在,如何创建新文档? - How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist? 如何创建新文档(如果不存在)并使用MongoDB NodeJS本机驱动程序返回新文档 - How to create a new document 'if not exists' and return the new document with MongoDB NodeJS native driver 更新mongodb文档,如果文档存在,否则创建 - Update mongodb document, if the document exists, else create 更新文档中的嵌入式数组(如果存在),否则创建一个新文档MongoDB NodeJS - Update an embedded array inside an document if it exists otherwise create a new document MongoDB NodeJS 新用户在检查唯一电子邮件和用户名后不保存到 MongoDB - New user don't save into MongoDB after checking unique email and username MongoDB 和 API 集成 - 如果不存在则创建新用户 - MongoDB and API integration - Create New User if Doesn't Already Exist Nestjs:Mongoose 文档中不存在属性 - Nestjs: Property doesn't exists in Mongoose document Redux 和 MongoDB 不创建新文档 - Redux and MongoDB dont create a new Document
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM