Kuyashii
Kuyashii

Reputation: 388

Which of these 2 MongoDB design choices is recommended?

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:

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:

Which design makes the most sense/would be the recommended approach in MongoDB?

Upvotes: 0

Views: 32

Answers (1)

Joe Drumgoole
Joe Drumgoole

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

Related Questions