node.js - Deep populate self referencing schema in mongoose -
i have self referencing employee schema in mongoose.
var mongoose = require('mongoose'); var schema = mongoose.schema; var employee = new schema({ name: string, description: { type: string, default: 'no description' }, manager: { type: schema.types.objectid, ref: 'employee', default: null }, reportee: [{ type: schema.types.objectid, ref: 'employee' }] });
an employee can manager & can have several reportee. if manager null employee treated top level employee.
i need created hierarchy based on model. struggling generate desired output.
so far have tried use popluate() & mongoose-deep-populate module unable desired output. wonder becuase have self referencing model. or may not using these 2 options properly.
this have tried deep-populate
module. seems populating reportee model not repotree of reportee model. in short populating 1 level of records.
employee.deeppopulate(employees, 'reportee.reportee.reportee.reportee.reportee', function (err, _employee) { employees.foreach(function (employee) { }); });
please suggest how can retrive employee hierarchy ?
to answer own question, using mongoose-deep-populate library.
to use need install module:
npm install mongoose-deep-populate
//register plugin var deeppopulate = require('mongoose-deep-populate'); employee.plugin(deeppopulate);
and use code:
employee.deeppopulate(employees, 'reportee.reportee.reportee.reportee.reportee', function (err, _employee) { employees.foreach(function (employee) { }); });
this load 5 levels of reportees have mentioned reportee.reportee.reportee.reportee.reportee
Comments
Post a Comment