mongoose-nested-set
A mongoose plugin implementing the nested set pattern for mongoose models
Usage
var mongoose = NestedSetPlugin = Schema = mongooseSchema; mongoose; var UserSchema = username: type: String; // Include pluginUserSchema; var User = mongoose;
Attributes
The plugin adds the following attributes to the model:
-
lft: holds the left value of the node in the tree
-
rgt: holds the right value of the node in the tree
-
parentId: holds the _id of the parent node
Options
The plugin supports the following options:
- groupingKey: a key to denote that elements in the tree belong to a group. This is helpful to maintain multiple trees within the same collection. Eg. in the tests we have two trees, grouped by the attribute 'organization' on the model, in that case we've given the { groupingKey: 'organization' } as options.
Examples
Examples are based on the following tree:
User;
For more examples, see our test suite.
API
Static methods
- Model.rebuildTree(rootNode, leftValueOfRootNode, callback)
Instance methods that return values:
The following methods return a boolean:
-
isLeaf()
-
isChild()
-
isDescendantOf(otherNode)
-
isAncestorOf(otherNode)
Instance methods that use a callback function:
The following methods must be used with a callback. The callback method will be called with two arguments: the first argument is the error object (if there was no error, it will be null) and the second argument is the data returned.
-
selfAndAncestors(callback)
-
parent(callback)
-
ancestors(callback)
-
selfAndChildren(callback)
-
children(callback)
-
selfAndDescendants(callback)
-
descendants(callback)
-
level(callback)
-
selfAndSiblings(callback)
-
siblings(callback)
Related Links/Resources
- Inspired by Rails nested_set library
- Mongoose Documentation
- Mongoose Plugins
- Tree used in test and examples
- Nested Set Model
- Storing Hierarchical Data in a Database Article
- Trees in MongoDB
Development
To run the tests:
npm test
Changelog
Feb 14, 2015: Version 0.0.7
- Converted methods to follow mongoose params model #11
Nov 23, 2014: Version 0.0.6
- New Feature: added groupingKey option
Jun 30, 2013: Version 0.0.5
- Added compound index on lft,rgt for selfAndDescendants and selfAndAncestors queries
- A few small refactorings of tests
Oct 26, 2012: Version 0.0.4
- Bug fixes
Oct 25, 2012: Version 0.0.3
- Bug fixes
Oct 25, 2012: Version 0.0.2
- Better tests
- Code cleanup
- Updated package.json to latest dependencies
- Added mongodb indexes on lft, rgt, and parentId
Authors
- Luc Castera: https://github.com/dambalah