【问题标题】:Update an array of objects that contains a unique value using Mongoose使用 Mongoose 更新包含唯一值的对象数组
【发布时间】:2019-08-05 17:36:03
【问题描述】:

我在包含对象数组的集合中有文档。数组中的每个对象都包含一个唯一字段“clinic_id”。我也在使用 mongoose-unique-validator。

我有一个 Node 路由,它接受 JSON 请求以将新对象推送到数组上。但是,只要数组中有现有对象,这就会失败。我在已经存在的对象上收到一个唯一约束错误。例如,如果我在数组中有一个 Clinic_id 为 1 的对象,并且我尝试为 Clinic_id 2 添加一个对象,我将收到一个错误,抱怨 Clinic_id 1 已经存在。就好像我在尝试创建一个重复条目,而不是仅仅向数组中添加一个新的非重复对象。

Mongoose 模式的一个示例:

  name: { type: String, required: true },
  org_id: { type: String, unique: true, required: true },     
  branch: [{
              name: { type: String, required: true },
              clinic_id: { type: String, unique: true, required: true },
              type: { type: String }
          } ]

Node Route 中包含的代码示例,它尝试将新对象推送到数组中:

  const orgId = req.params.id;

  Org.findOne({ org_id: orgId }).then(org => {

    // Get org_id from URL and add to JSON body
    req.body.org_id = orgId;
    // Push Branch Object onto the array
    org.branch.push(req.body);

    org
      .save()
      .then(savedOrg => {
        res.json({ status: 'SUCCESS', id: savedOrg._id });
      })
      .catch(err => {
        const error = JSON.stringify(err);
        res.status(500).json({ status: 'ERROR', desc: error });
      });
  });

mongoose-unique-validator 产生的错误文本:

{ ValidatorError: 错误,预计 clinic_id 是唯一的。价值: 100 在新的 ValidatorError ...

附加信息:节点 v10.15.1 / mongoose 5.2.1 / mongoose-unique-validator 2.0.2

【问题讨论】:

  • 是分支它自己的模型,还是你试图让它成为一个对象数组?
  • 组织模型中包含的对象数组。如果我最初添加所有内容,它就可以正常工作。但是每当我尝试将一个对象(包含另一个分支)附加到数组时,它都会失败,因为 Clinic_id 已经在数组中,但唯一验证失败。
  • 那是因为你真的不应该那样使用猫鼬。总体思路是充分发挥 mongodb 的潜力。我将创建一个关于如何解决它的答案,如果您不喜欢该解决方案,希望其他人会回答。

标签: javascript node.js mongodb mongoose


【解决方案1】:

您应该创建一个具有以下属性的新模型:

{
    name: { type: String, required: true },
    clinic_id: { type: String, unique: true, required: true },
    type: { type: String }
}

现在,它变得更加容易,因为您无需单独参考诊所。您可以在此文档中添加 Org 的 id,但根据您的原始实现,我假设您不需要它。

当你去创建一个诊所时,你只需将 id 添加到父文档(Org)中。

您的组织中的字段将更改为:

branch: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Clinic'
}]

现在,每当您创建一个分支时,您只需将生成的对象(您甚至不需要指定 _id,它会为您完成)推送到正确的组织中,您就会得到您想要的列表。

当你想找到分支时:

Org.find(condition).populate('branch')

你会得到你想要的完全相同的结果。

现在,当我提到 mongoose 时,我的意思是如果你像这样导入它:

const mongoose = require('mongoose');

【讨论】:

    猜你喜欢
    • 2013-04-02
    • 2013-03-19
    • 1970-01-01
    • 2014-04-03
    • 2019-03-25
    • 2019-12-15
    相关资源
    最近更新 更多