MongoDB Embedded Document : ExtJS 5 and nested Model’s

We describe here a way to work with Embedded Documents and ExtJS Models, especially on the Parsing (GET) part. Embedded documents are a powerful feature of MongoDB, my favorite. A nice alternative to OneToMany SQL Join.

For example, based on a JSON data from a GET query, if we have:

{
    "success": true,
    "user": [{
        "id": 1,
        "name": "Philip J. Fry",
        "last_post": {
            "title": "Post 1", posted:"2015-03-03T12:45:14Z"
        }
    }]
}

In ExtJS, the models are:

Ext.define('MyApp.model.User', {
    extend: 'Ext.data.Model',

fields:[
   { name: 'id', type:'int' }
  ,{ name: 'name', type:'string' }
  ,{ name: 'last_post', reference:'Post' }
]

}); // eo MyApp.model.User

and

Ext.define('MyApp.model.Post', {
    extend: 'Ext.data.Model',

fields:[
  { name: 'title', type:'string' }
  ,{ name: 'posted', type:'date' }
]

}); // eo MyApp.model.Post

At this point, even if we could access last_post fields (last_post.title), “date” field is not parsed and so, not transformed into a “Date” object. There are couple of solutions, but my favorite and most efficient is the following: use “convert” function for the “last_post” field.

So, User model becomes:

Ext.define('MyApp.model.User', {
    extend: 'Ext.data.Model',

fields:[
   { name: 'id', type:'int' }
  ,{ name: 'name', type:'string' }
  ,{ name: 'last_post', 
     // Here is the trick... =>
     convert: function(value) { 
       return Ext.create("MyApp.model.Post", value).data; 
     } 
   }
]

}); // eo MyApp.model.User

By this way, “transformation” is hold by the “convert” function and works efficiently.

References