Reputation: 388
I have 2 models: Supplier
and Supplier type
. The client should be able to retrieve all Suppliers
belonging to a particular Supplier Type
:
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' }],
};
Design 1:
Supplier
contains a reference to the assigned Supplier Type
object.Supplier Type
object contains object references to all the Suppliers
that have the Supplier Type.Supplier Type
document, let's say Vegetables
and contained in the response, among other fields, will be a list of Suppliers
.With this approach, each time a new Supplier is saved, at least one other DB operation would be needed to update the Suppliers
array on the Supplier Type
object.
Design 2:
Suppliers
reference array from Supplier Type
objectSupplier
contains a reference to the assigned Supplier Type
object, as in design 1.Supplier
document with a parameter specifying the Supplier Type
i.e. GET /suppliers?supplier-type=Vegetables
Which design makes the most sense/would be the recommended approach in MongoDB?
Upvotes: 0
Views: 32
Reputation: 1348
I see no reason to split these two objects into separate collections. Embed the SupplierType
inside the Supplier
object. If a Supplier
can be of more than one SupplyType
you can extend that object into an array.
Now when you get any Supplier
you automatically get their SupplierType
without the need for a join and/or a second query.
Want to find all the Supplier
docs by SupplyType
? Query on the SupplyType
field and a single cursor will return all the relevant suppliers.
Apply indexes to either field if the number of items is large to improve performance.
Upvotes: 1