Permalink
Browse files

modifying ancestor tree adding required static methods for children a…

…nd directChildren
  • Loading branch information...
1 parent cccd92b commit 4f7a6f569d5dd59a8bf1050fc3449b488838c644 @mariuskubilius committed Apr 25, 2013
Showing with 49 additions and 3 deletions.
  1. +46 −0 lib/ancestorTree.js
  2. +3 −3 package.json
View
@@ -129,6 +129,52 @@ ancestorTree = function(schema){
return this.model(this.constructor.modelName).find({_id: {$in: this.ancestors}}, fields, cb);
});
+ /**
+ * Static Methods for schema
+ */
+ schema.statics = {
+
+ /**
+ * Find direct children
+ * @param {ObjectId} [id] _id of parent item, or null if no parent exists.
+ * @param {Object} [options] pass options here
+ * @param {Function} [cb] Callback function.
+ */
+ directChildren: function (parent, options, cb) {
+ if(arguments.length === 2 && typeof arguments[1] === 'function'){
+ cb = options;
+ options = {};
+ }
+ options.fields = options.fields || {'title':1, 'slug':1};
+ options.sort = options.sort || {'title': 1};
+ this.find({parent: parent})
+ .sort(options.sort)
+ .select(options.fields)
+ .exec(cb)
+ },
+
+ /**
+ * Find all children _ids and return them as an array
+ * @param {ObjectId} [current] items _id which children you are looking.
+ */
+ childrenIdArray: function (current, cb) {
+ var nodes = [current];
+ this.find({ancestors: current})
+ .select('_id')
+ .stream()
+ .on('data', function(doc){
+ nodes.push(doc._id)
+ })
+ .on('error', function(err){
+ cb(err, nodes);
+ })
+ .on('close', function() {
+ cb(null, nodes)
+ });
+ }
+}
+
+
};
/**
* @todo write tests for statics.
View
@@ -1,6 +1,6 @@
{
"name": "lbg-mongoose-utils",
- "version": "0.0.4",
+ "version": "0.0.5",
"description": "a collection of plugins used in my projects for mongoose",
"main": "index.js",
"bin": {},
@@ -11,15 +11,15 @@
"test": "make test && make clean"
},
"dependencies": {
- "mongoose": "~3.5.x"
+ "mongoose": "~3.6.x"
},
"devDependencies": {
"mocha": "~0.10.0",
"async": "latest"
},
"keywords": [
"mongoose",
- "mongoose 3.5.x",
+ "mongoose 3.6.x",
"slugs",
"unique-slugs",
"array of ancestors",

0 comments on commit 4f7a6f5

Please sign in to comment.