_ = require 'underscore' mongoose = require("mongoose") mongooseHelper = require("mongoose-helper") async = require 'async' populationPlugin = (schema, options) -> cached = null getPopulationFields = ()-> return cached if cached? cached = _.chain(schema.tree) .map( (v, k)-> v._fieldName = k return v ) .filter( (v, k)-> return _.isArray(v) or v.ref? ) .pluck('_fieldName') .value() return cached schema.methods.getNestedJson = (_callback)-> console.log 'start with', @_modelName popFields = getPopulationFields() return _callback @toJSON() unless popFields?.length popQuery = _.map popFields, (fieldName)-> {path: fieldName} mongoose.models[@_modelName].findById(@_id) .populate(popQuery) .exec (err, doc)-> async.eachSeries(popFields, (field, innerCallback)-> return innerCallback null unless doc[field].length _.each doc[field], (model, index, array) -> mongoose.models[model._modelName].findById model._id, (err, nestedModel) -> nestedModel.getNestedJson (JSON) -> doc[field][index] = JSON if index is array.length - 1 innerCallback null, {} , (err, res) -> _callback doc ) module.exports = populationPlugin