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_idto be unique. Value:100at new ValidatorError ...
Additional Information: Node v10.15.1 / mongoose 5.2.1 / mongoose-unique-validator 2.0.2