1

I am using Lawnchair JS from http://brian.io/lawnchair/ in my Phonegap Application to manage my database records. I am new to document stores but experienced with traditional relational databases. How should I go if I wanted to reference one record on another record. For example: I have multiple records for food ingredients and I have multiple records for recipes, in a recipes JSON, is there a way to reference an ingredient record?

Andre Garzia
  • 983
  • 2
  • 11
  • 19

1 Answers1

3

To achieve what you want with a json document store like lawnchair, you just need to store the key name of the referenced document inside your document.

For instance you will have those food ingredient documents:

{key:'fi_1', name: 'rice', id: 1}
{key:'fi_2', name: 'corn', id: 2}

and those recipe documents:

{key:'r_332', ingredients: ['fi_1', 'fi_54'], name: 'risotto', id: 332}
{key:'r_333', ingredient: ['fi_12'], name:'cookie', id: 333}

you could store the list of all your recipes inside one document:

{key:'cookbook', recipes: ['r_1', 'r_2', .... 'r_332', 'r_333', .... ] }

you can then retrieve the cookbook document:

store.get('cookbook', function(data) {
    var recipes = data.recipes;
    // do something with the list of all recipes
});

and look for a recipe to retrieve its ingredients:

store.get('r_332', function(data) {
    var ingredients = data.ingredients;
    for (ingredient_key in ingredients) {
        store.get(ingredient_key, function(ingredient_data) {
             var name = ingredient_data.name;
             var id = ingredient_data.id;
             // do something with each ingredient
             alert('ingredient: ' + name + ' - id: ' + id);
        }
    }
});

In the lists above, instead of storing the full key name of the referenced documents you could just store their ids as you are supposed to know their type and how to re-create the keyname from that (food ingredient : 'fi_' prefix followed by id, recipe : 'r_' followed by id..).

chrisben
  • 955
  • 8
  • 16
  • Thanks very much for the detailed answer, it really helped me. Now, let me see if I can figure a safe way to create ids, think I will go with it-always-increment approach =) – Andre Garzia Jun 11 '12 at 16:14
  • sure, auto-increment is the most natural way to create simple ID numbers. – chrisben Jun 12 '12 at 08:27