Storing object references in JSON Storing object references in JSON sqlite sqlite

Storing object references in JSON


Traditional table based relation databases have solved this problem. Each record/document that could be referenced in multiple contexts is stored in it own table/collection with an id. That id is referenced by other objects in their own collections.

JSON itself will only hold raw data, so as you note, object references that change is not something JSON can handle.

So the question becomes, is the data a relationship between first order objects? Or is it nested/embedded in another object?

In your example, a project has many people, a project has many cats, and people has many projects. So because people and projects both need to be referenced by multiple other objects, each resource should be it's own resource, reference by a foreign key.

// projects.json[  {    id: 4    name: 'homework',    person_ids: [1,2,3],  }]// people.json[  {    id: 1,    name: 'Bob',    project_ids: [4,5,6],  }]

A good case for embedding might be comments on a project. In this case, you always access the comments through the projects. And because a comment can only ever belong to a single project, embedding it makes more sense.

// projects.json[  {    id: 4    name: 'homework',    person_ids: [1,2,3],    comments: [      {         person_id: 1,         message: 'My dog ate it'      ]    ]  }]

I'd recommend reading up on how Mongoid handles relations. It's a ruby wrapper for MongoDB, but the docs explain how it structures the collections to enable relationships. You might find it quite helpful to get your head around how this would work.