require underscore mongoose require mongoose mongooseHelper require mo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
_ = 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