diff --git a/lib/nested_set.js b/lib/nested_set.js index ef06acb..5776cd3 100644 --- a/lib/nested_set.js +++ b/lib/nested_set.js @@ -412,6 +412,26 @@ var NestedSetPlugin = function(schema, options) { callback(err, nodes.length); }); }); + + // Returns the length of the subtree under this object + schema.method('treeLength', function(callback) { + var self = this; + self.selfAndDescendants(function(err, nodes) { + var levels = []; + nodes.forEach(function (node) { + node.level(function (err, value) { + levels.push(value); + if (levels.length == nodes.length) { + var min = Math.min.apply(null, levels); + var max = Math.max.apply(null, levels); + var length = (max - min) + 1; + callback(err, length); + } + }); + }); + }); + }); + }; module.exports = exports = NestedSetPlugin;