【问题标题】:Create new document if username or email doesn't exists in MongoDB如果 MongoDB 中不存在用户名或电子邮件,则创建新文档
【发布时间】:2019-12-10 17:06:13
【问题描述】:

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

如果用户名或电子邮件不存在,我正在尝试插入新文档。

我的代码工作正常,唯一的问题是我的架构没有按我的意愿组织。我希望username 出现在email 之前。

问题

我已经尝试解决这个问题,但我没有成功,但问题正是在$or查询operator,我不知道为什么它会改变我的架构!!

这是我的代码

   //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();
  });

非常感谢任何信息,谢谢

【问题讨论】:

  • 只使用 $set 而不是 $setOnInsert 会发生什么?
  • 它显示同样的东西,问题在查询$or我不知道为什么它改变了架构!
  • 为什么要在email 之前出现username? MongoDB 文档是一个 JSON 对象。您可以直接以user.username 访问JSON 对象中的username。它或多或少类似于哈希表。我真的没有明白你的意图,在 JSON 对象中排序解决了什么问题。
  • 我知道,就像你说的,没有问题。这只是为了组织我的文档的结构,我会一直这样,直到我找到更好的答案或如果不存在另一种插入方式。

标签: node.js mongodb


【解决方案1】:

为了使我的文档井井有条,首先我在其中调用 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();
       }
     });

结果

我不确定我的代码是否干净并遵循良好的做法,但目前这是一个很好的解决方案。

【讨论】:

    【解决方案2】:

    On Else if condition 请仅更新!res.upserted

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多