3

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

3
  • Is branch it's own model, or are you trying to make it an array of objects? Commented Mar 14, 2019 at 20:59
  • An array of objects contained in the Org Model. It works just fine if I add everything initially. But anytime I try to append an object ( containing another branch ) to the array it fails because the clinic_id 's already in the array fail unique validation. Commented Mar 14, 2019 at 21:06
  • That's because you aren't really supposed to use mongoose that way. The general idea is to use mongodb to its fullest potential. I'm going to create an answer on how I would solve it, and if you don't like the solution, hopefully someone else will answer. Commented Mar 14, 2019 at 21:11

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.