New to Meteor and MongoDB, coming from a relational database background. This question actually reflects my puzzle at how relations are handled in MongoDB.
Example: I want to insert a recipe into a collection of recipes, which in this case is a comma delimited string of multiple ingredients. I want, however, to insert these ingredients into a collection of ingredients at the same time. And I would like to have the recipe refer to the ingredients in the ingredients collection, so that, say, if I got an ingredient's spelling wrong the first time, I could update it in the ingredients collection later and have all recipes that use that ingredient updated as well.
It seems that the way to do it is to include the ingredients collections as subdocuments in the recipes collection.
However, I'm not sure how I can actually implement that. Sample code in JS using Meteor follows:
Recipes = new Mongo.Collection("recipes");
Ingredients = new Mongo.Collection("ingredients");
Template.body.events({
"submit .new-recipe": function(event) {
// Prevent default browser form submit
event.preventDefault();
// Get value from form element
var text = event.target.text.value;
var splitText = text.split(",");
var nInputs = splitText.length;
var recipe = [];
for (var i = 0; i < nInputs; i++) {
// Insert an ingredient into the ingredients collection
Ingredients.insert({
itemName: splitText[i].trim(),
createdAt: new Date()
});
recipe.push(splitText[i]);
}
// Insert the list of ingredients as a recipe into the recipes collection
Recipes.insert({
recipe: recipe,
createdAt: new Date()
});
// Clear form
event.target.text.value = "";
}
});
Obviously, the above doesn't do the job correctly. It severs the relationship between the ingredients and the recipes. But how can I maintain the relationship? Do I put the Ids of the ingredients into the recipes collection at the time of inserting the ingredients? Do I have the entire ingredient document inserted as a part of a recipe document into the recipes collection, at the time of inserting the ingredients?