kevinius
kevinius

Reputation: 4618

mongoDB + mongoose: choosing the right schema for hierarchical data

I'm new to mongoDB and in a node project i'm using mongoose to create a schema for my database. I have come to understand that in my case i should be using embedded data instead of by reference. (http://docs.mongodb.org/manual/core/data-modeling-introduction/)

The structure that i need to store in the database is something like this:

Coming from a mySQL world, i'm trying to understand the noSQL database concepts and i was wondering how one would design the mongoose schema.

Thx,

Upvotes: 1

Views: 1159

Answers (2)

s.d
s.d

Reputation: 29436

You can nest documents, and document arrays in a MongoDB document:

db.books.findOne();

can return a JSON:

{
  isbn:"253GHST78F6",
  title:"some book",
  author:"Earnest Hemmingway",
  chapters:[
   {title:"chapter 1",content:"http://api.com/chapters/1.html"},
   {title:"chapter 2",content:"http://api.com/chapters/2.html"}
  ]
}

But, there are a few more things to keep in mind when modeling a collection in MongoDB:

  1. Model data as close as possible to what will be asked for: There are no Joins in MongoDB, so, try to keep all such data together (pre joined), that is supposed be queried together in future.

  2. Nesting is good for queries but nested update and search is bad:

    1. Indexing and searching inside nested documents, especially arrays, will be expensive.
    2. Avoid placing any data in nested arrays, that is very frequently updated.
  3. There are no Foriegn Keys in MongoDB. So, if you have multiple copies of same document nested under different collections, keeping all of them updated is your responsibility.

Upvotes: 1

Miroslav Trninic
Miroslav Trninic

Reputation: 3455

First take a look at this Martin Fowlers excellent video:

I think there is no better authority that can explain nosql, then Fowler. Especially knowing his sql background.

Second, MongoDB follows json schema. If you know how to work with json, you will know how to work with nosql (mongodb). Basic thing that needs to be understand is that Mongo schema is expressed in a language that is using it. So, if you are using NodeJS with Mongo, you still have objects and array to work with. In simple words, Mongo is not forcing any particular schema. It is on developer to create his scheme based on his language/mongo driver.

So how would you express you data logic in your language ? If it is in form of JS object, then move that form to db.

I really like MongoDB, becuse it can be combined with some great JS tools like Underscore.js for all kind of data manipulations.

Upvotes: 1

Related Questions