I am using Mongoose ODM. Having 2 schemas - I would like to ensure that when I create a new Supplier, that it’s ID
is added to the reference object array - suppliers
on SupplierType.
Supplier
:
name: {
type: String,
required: true,
minlength: 2,
maxlength: 255,
},
...
supplier_type: { type: ObjectId, ref: 'SupplierType' },
}
SupplierType
:
name: {
type: String,
required: true,
minlength: 2,
maxlength: 50,
},
suppliers: [{ type: ObjectId, ref: 'Supplier' }],
};
When a user makes a POST to create a new Supplier
- I execute the following:
const supplier = new Supplier({
name: req.body.name,
...
supplier_type: req.body.supplier_type,
});
await supplier.save();
This, of course, does not update/add the new Supplier
to the suppliers
array on Supplier Type
, so I do the following:
// Save the supplier
await supplier.save();
// Add the new Supplier's ID to the `suppliers` array on the `Supplier Type`
await SupplierType.update(
{
_id: supplier.supplier_type,
},
{ $push: { suppliers: supplier.id } }
);
I’d like to know if this is best practice and if not, I’d like to know the best way to achieve the same goal?