简体   繁体   中英

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". 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. 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. 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:

{ ValidatorError: Error, expected clinic_id to be unique. Value: 100 at new ValidatorError ...

Additional Information: 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.

When you go to create a clinic, you just add the id to the parent document (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.

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:

const mongoose = require('mongoose');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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