Using Backbone.js with MongoDB

MongoDB provides data in the Mongo DB Extended JSON format, which looks like following:

{
  _id: {
    "$oid": "<id>"
  },
  first_name: 'Vadim',
  last_name: 'Mirgorod'
}

Everything is OK expect ID, which could not be processed by the Backbone.js out of the box. In this post we are going to learn a solution for solving this problem.

How-to

Such problem can be easily solved by using of Backbone.js extension known as mongo-db, which was created by your obedient servant. To enable MongoDB support you should include this extension to your project and mix Backbone.MongoModel.mixin with Backbone.Model prototype.

_.extend(Backbone.Model.prototype, Backbone.MongoModel.mixin);

This will make all Backbone.Model children to support MongoDB Extended JSON.

Backbone-mongodb overrides Backbone.parse() and Backbone.sync() methods to transform MongoDB Extended JSON into a regular one and back accordingly. Check out the source code of backbone-mongodb.js to understand how it works.

See also

Similar Entries