Skip to content

Instantly share code, notes, and snippets.

@eyy
Created July 3, 2013 11:04
Show Gist options
  • Save eyy/5917053 to your computer and use it in GitHub Desktop.
Save eyy/5917053 to your computer and use it in GitHub Desktop.
mongoose recursive schema
schema.statics.findRecursive = function(cb) {
this.find({ show: true, menu: true })
.select('order parent url title')
.sort({ parent: -1, order: 1 })
.lean()
.exec(function(err, items) {
if (err) cb(err);
var o = {},
arr = [];
items.forEach(function(item) {
item.sub = [];
o[item._id] = item;
});
for (var i in o) {
var item = o[i];
if (item.parent) {
o[item.parent].sub.push(item);
delete o[i];
}
}
for (var i in o) {
arr.push(o[i]);
}
cb(null, arr);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment