Domanda

I'm not sure how to construct this database in mongoDB. entity relational model recipe database

Because of my relational database background I'd think the database would be structured like this:
2 collections:

  1. Users
    • basic props including _id
  2. Recipes
    • relevant info like title, ingredients, etc.
    • a reference to a user document

If I simply throw a _id from a user (or use a proper DBRef) into the uploaded_by field for a recipe it is very difficult to do join-like operations. Specifically, I need to get the user name for all recipes. I would be returning an array of objects with this format:

{title:'chocolate chip cookies',
desc:'yummy soft cookies',
uploaded_by:'john doe'}

To do this, would I have to do a query for each recipe to find then name of the user based on the reference, and then return a custom object with the name of the user, and the other information? This sounds too expensive and makes me think I should just stick to relational databases. Is there a more efficient way to do this?

È stato utile?

Soluzione

Chris,

Your idea is what I suggest you do.

The power of mongodb comes from having denormalized data (vs. normalized data, where the goal is to minimize redundancy). When you query mongo for data, you want to query the database only once, and get back everything you need. There is no way to do this in mongodb if you have the data you need spread out over several collections (at least no efficient way that I know of). I think you should consider having an "uploaded_by" field in your Recipes collection that contains the formatted first/last name of the uploader (as you have concluded). You will also need a field for each user (say, uploaded_recipes) that contains an identifier (or collection of identifiers) to the recipes each user has uploaded. That way, you do not need to perform joins on your data. This would be the "mongodb way" of setting up your database.

To answer your persistence problem, the process for handling changes to a user's name would need to be dealt with differently. The procedure that implements changes to a user document must also update the "uploaded_by" field for each recipe a user has uploaded (you traverse over the uploaded_recipes field for that user). The idea here is that you add complexity to the insertion process to simplify and improve queries to your database.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top