0

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...

    }      
  },
});
  • Ok, first: please show at least a modicum of respect by putting at least as much effort into your question as you expect others to put into their answers. It took me a while to even make it readable. You might find ESR's excellent essay How To Ask Questions The Smart Way helpful. Since this answer is going to take a while, please have a bit of patience. – Markus W Mahlberg Nov 7 '15 at 18:48
1

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:

{
  "_id": new ObjectId(),
  "name": "Katsuo no Tataki",
  "desc": "Lightly Broiled Bonito",
  "tags": ["fish","jp"]
  "ingredients": [
    { "name": "Bonito Filet", qty: "1/2" }
    { "name": "onion", qty: "1/2"},
    { "name": "garlic", qty: "2 cloves"}
  ]
}

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

db.dishes.find({"ingredients.name":/garlic/i})

or, to find recipes containing the fish tag:

db.dishes.find({"tag":/fish/i})

Note that I used a case insensitive regex search.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.