I have a fairly large data set, where each element has a field hierarchywith an attribute children, which is an array of links to other elements. I want to get all the top parent elements and fill them up to all sheets.
Item = new Schema({
...,
hierarchy: {
children: [{
type: mongoose.Schema,
ref: 'Item'
}],
...
})
Filling only fills one level and does not continue through the tree. I also tried mongoose-deep-populate , but couldn't get it to work. Can I write a recursive function to fill in all the fields? One of my ideas was to write something like this:
items = _.map(items, function(item){
return populateChildren(item);
});
function populateChildren(item){
if(item.hierarchy && item.hierarchy.children && item.hierarchy.children.length > 0){
item.hierarchy.children = _.map(item.hierarchy.children, function(child){
console.log(count++, child);
return Item.findById(child).exec(function(err, child){
return populateChildren(child);
})
});
}
return item;
}
Any ideas on how I can fill the hierarchy?
source
share