Permalink
Browse files

Adding schema.pre('remove' hook to not delete items with children.

  • Loading branch information...
1 parent dba906d commit 5e5182772bdd8bcaeaf7dc96677f11039333717b @mariuskubilius committed Jan 23, 2013
Showing with 39 additions and 1 deletion.
  1. +12 −0 lib/ancestorTree.js
  2. +27 −1 test/ancestorTree.test.js
View
@@ -87,6 +87,18 @@ ancestorTree = function(schema){
}
});
+ schema.pre('remove', function(next){
+ this.collection.count({ancestors: this._id},function(err, count){
+ if(err) return next(err);
+ if(count > 0 ){
+ return next(new Error('Please delete/move all children before proceeding'));
+ }
+ else {
+ return next();
+ }
+ });
+ });
+
schema.method('findDirectChildren', function(opts, cb) {
if(arguments.length === 1 && typeof arguments[0] === 'function'){
cb = opts;
View
@@ -163,7 +163,7 @@ describe('ancestorTree', function () {
},
function(cb) {
doc.findChildren(function(err, children){
- assertStrictEqual(err, null, 'should work with one argument only.');
+ assert.strictEqual(err, null, 'should work with one argument only.');
cb(err);
});
}
@@ -188,6 +188,32 @@ describe('ancestorTree', function () {
});
});
+ it('should not delete items with children.', function(done){
+ MockModel.findOne({_id: c._id}, function(err, doc){
+ doc.remove(function(err, res){
+ assert.strictEqual('Please delete/move all children before proceeding', err.message);
+ MockModel.count({_id: c._id}, function(err, count){
+ assert.strictEqual(err, null);
+ assert.strictEqual(count, 1);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should Delete items without children.', function(done){
+ MockModel.findOne({_id: asc._id}, function(err, doc){
+ doc.remove( function(err, res){
+ assert.strictEqual(err, null);
+ MockModel.count({_id: asc._id}, function(err, count){
+ assert.strictEqual(err, null);
+ assert.strictEqual(count, 0);
+ done();
+ });
+ });
+ });
+ });
+
});
});

0 comments on commit 5e51827

Please sign in to comment.