I just started to learn MongoDB database and for my project.
I am trying to implement a MongoDB reference schema.
In my Menu table I would have a food ingredients attributes where it will store the food ingredients.
I am confused about designing my schema.
How am I going to build the schema with the food ingredients in Menu table?
Because it might be 100 ingredients, do I need to create an attribute for each of them ?
Or I can make one string attribute where I am going to store everything?
Here is an example of it.
var Menu = new Schema({
foodTitle: String,
foodIng: {
title: String,
ingredients: {
rice: String,
beans: String,
meat: String,
cheese: String,
// etc...
}
},
});
Best Answer
As far as I have understood your question, you are trying to create a model for dishes and list their ingredients.
You should never, ever use values as keys. With a relational database, would you create a table which has a column for each imaginable ingredient? Hardly.
Furthermore, while redundancy isn't necessarily a bad thing, it is in keys. In a collection called "dishes" or "food", it is natural that an ingredient does not refer to a chemical compound, right?
So, here is how I'd model a dish:
When displaying a dish, you simply iterate over the
ingredients
array, displaying both name and qty.In order to find all dishes which contain garlic, you simply do
or, to find recipes containing the
fish
tag:Note that I used a case insensitive regex search.