简体   繁体   English

使用 Mongoose 更新包含唯一值的对象数组

[英]Update an array of objects that contains a unique value using Mongoose

I have documents in a collection that contain an array of objects.我在包含一组对象的集合中有文档。 Each object in the array contains a unique field "clinic_id".数组中的每个对象都包含一个唯一的字段“clinic_id”。 I'm also using mongoose-unique-validator.我也在使用猫鼬唯一验证器。

I have a Node route that accepts a JSON request to push a new object onto the array.我有一个 Node 路由,它接受一个 JSON 请求来将一个新对象推送到数组上。 However, this fails anytime there is an existing object in the array.但是,只要数组中有现有对象,这就会失败。 I get a unique constraint error on the already existing object(s).我在已经存在的对象上得到一个唯一的约束错误。 For instance if I have an object in the array with clinic_id 1 and I attempt to add an object for clinic_id 2, I will receive an error complaining that clinic_id 1 already exists.例如,如果我在数组中有一个带有 Clinic_id 1 的对象,并且我尝试为 Clinic_id 2 添加一个对象,我将收到一个错误,抱怨 Clinic_id 1 已经存在。 It's acting as if I'm attempting to create a duplicate entry rather than just adding a new non duplicated object to the array.它的行为就像我试图创建一个重复的条目,而不仅仅是向数组添加一个新的非重复对象。

An example of the Mongoose schema:猫鼬模式的一个例子:

  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 }
          } ]

An example of code contained within the Node Route that attempts to push a new object onto the array:尝试将新对象推送到数组的节点路由中包含的代码示例:

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

Text of the error produced by mongoose-unique-validator: mongoose-unique-validator 产生的错误文本:

{ ValidatorError: Error, expected clinic_id to be unique. { ValidatorError: 错误,期望clinic_id是唯一的。 Value: 100 at new ValidatorError ...值: 100在新的 ValidatorError ...

Additional Information: Node v10.15.1 / mongoose 5.2.1 / mongoose-unique-validator 2.0.2附加信息:Node v10.15.1 / mongoose 5.2.1 / mongoose-unique-validator 2.0.2

You should create a new Model with the following properties:您应该创建一个具有以下属性的新模型:

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

Now, it's even easier because you don't need to reference the clinic independently.现在,它更容易了,因为您不需要独立参考诊所。 You could add the id of the Org on this document, but I'll assume you don't need it based on your original implementation.您可以在本文档中添加 Org 的 id,但根据您的原始实现,我假设您不需要它。

When you go to create a clinic, you just add the id to the parent document (Org).当您去创建诊所时,您只需将 id 添加到父文档(Org)。

The field in your Org will change to:您组织中的字段将更改为:

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

Now, whenever you create a branch, you simply push the resulting object (you don't even need to specify _id, it will do it for you) into the correct org, and you will have the list you want.现在,无论何时创建分支,您只需将结果对象(您甚至不需要指定 _id,它会为您完成)推送到正确的组织中,您将拥有所需的列表。

When you want to find the branches:当你想找到分支时:

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

and you will get the exact same result that you want.你会得到你想要的完全相同的结果。

Now, when I refer to mongoose , I mean if you import it like:现在,当我提到mongoose ,我的意思是如果你像这样导入它:

const mongoose = require('mongoose');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM