As someone transitioning from a relational database background to Meteor and MongoDB, I'm facing the challenge of understanding how relationships work in MongoDB. Specifically, I am puzzled about how to handle relations between collections in MongoDB.
For instance, let's say I want to add a recipe to a collection of recipes, where each recipe is a comma-separated list of ingredients. However, I also want these ingredients to be added to a separate collection of ingredients simultaneously. Additionally, I want the recipe to reference the ingredients in the ingredient collection so that if there are any updates to an ingredient, it automatically reflects in all recipes.
One way to achieve this could be by including the ingredients collection as subdocuments within the recipes collection.
Despite this approach, I'm unsure about the implementation process. Below is a snippet of JavaScript code using Meteor:
Recipes = new Mongo.Collection("recipes");
Ingredients = new Mongo.Collection("ingredients");
Template.body.events({
"submit .new-recipe": function(event) {
// Avoid default browser form submission behavior
event.preventDefault();
// Get input 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++) {
// Add an ingredient to 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 content after submission
event.target.text.value = "";
}
});
The above code does not establish the desired relationship between ingredients and recipes. To maintain this connection, should I include the ingredient Ids in the recipe collection when adding ingredients? Or maybe insert the entire ingredient document as part of the recipe document in the recipes collection during ingredient insertion?