MongoDB Relationships – Structuring in Node.js

mongodbnode.js

I am also using Node – which I am not the most familiar with – if the articles/books/tutorials pertained to this also – that would help even more.

I come from a mostly MySQL background – but in this api, all data is going to be served as JSON – so at first glance, using Mongo made a lot of sense (I could be wrong). One thign I have been unable to wrap my head around though, is relational models. e.b. Object has many Assets.

To use some examples most people would be familiar with, let's assume I am trying to do something like:

  • Select a blog post and all of its comments. or
  • Select a photo gallery and all of its photos

Is it as simple as storing a call back inside of my assets like this?:

Photo {
    __id: 5,
    content: '...',
    gallery_id: 9 
}

And performing a .find({ gallery_id: 9 })?

I know this would work, but is that best practice? I am very new to Document Databases, and have not seen much on this particular topic.

Best Answer

Coincidentally, I am in the process of thinking through a new application using Node and MongoDB.

I have lightly used MongoDB in the past and found the MongoDB documentation data modeling to be a great starting point. The approach that you describe, storing a reference in the parent and using a second find to get the referenced items, is a perfectly good way to go about it, if you choose to make use of references rather than directly embedding the children in the parent object.

However, there might be some better ways to go at this. I have been looking into using Mongoose as an Object Document Mapper (ODM). It is the officially supported ODM for Node per the MongoDB documentation.

It provides a number of useful features, particularly if you are building a fairly complex model within the application, including pseudo-joins using the populate function. The population capability provides a more structured approach to managing references allowing for retrieval of parent and children in one step.

Related Topic