Skip to content Skip to sidebar Skip to footer

Mongodb - Insert Into Two Collections, One Collection Referencing The Other As Subdocument

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 inse

Solution 1:

It sounds like you need a simple relational model between two collections. This is typically accomplished by storing the _id of one collection as a value in another. In your case, I'd recommend storing the ingredient ids as an array in the recipe. I see a few issues with your initial attempt:

  1. The existence of an ingredient is not being checked prior to insertion. So two recipes using "sugar" would insert two sugar documents - I assume this is not your intention.

  2. The insert is happening on the client, but unless you are publishing your whole ingredient collection, the client can't be the authority on which ingredients actually exist (following from 1).

  3. You are using the client's timestamp when doing the insert. What if their clock is wrong? There's actually a package that deals with this, but we can solve all of the above using a method.


I'd recommend splitting the text input on the client and then issuing a Meteor.call('recipes.insert', ingredientNames), where the method implementation looks something like this:

Meteor.methods({
  'recipes.insert': function(ingredientNames) {
    // Make sure the input is an array of strings.check(ingredientNames, [String]);

    // Use the same createdAt for all inserted documents.var createdAt = newDate;

    // Build an array of ingredient ids based on the input names.var ingredientIds = _.map(ingredientNames, function(ingredientName) {
      // Trim the input - consider toLowerCase also?var name = ingredientName.trim();

      // Check if an ingredient with this name already exists.var ingredient = Ingrediends.findOne({itemName: name});
      if (ingredient) {
        // Yes - use its id.return ingredient._id;
      } else {
        // Insert a new document and return its id.returnIngrediends.insert({
          itemName: name,
          createdAt: createdAt
        });
      }
    });

    // Insert a new recipe using the ingredient ids to join the// two collections.returnRecipes.insert({
      ingredientIds: ingredientIds,
      createdAt: createdAt
    });
  }
});

Recommended reading:

Post a Comment for "Mongodb - Insert Into Two Collections, One Collection Referencing The Other As Subdocument"