Skip to content

Instantly share code, notes, and snippets.

@RobertWHurst
Created August 14, 2015 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RobertWHurst/aee50ec21bc49ce345fa to your computer and use it in GitHub Desktop.
Save RobertWHurst/aee50ec21bc49ce345fa to your computer and use it in GitHub Desktop.
Mongoose Soft Remove Plugin
var Model = require('mongoose').Model;
function softRemove(schema) {
if (!schema.path('isRemoved')) {
schema.add({ isRemoved : { type: Boolean, index: true, default: false } });
}
if (!schema.path('removedAt')) {
schema.add({ removedAt : { type: Date, index: true } });
}
schema.static('remove', function(conditions, cb) {
var softRemove = true;
if (conditions.$softRemove !== undefined) {
softRemove = conditions.$softRemove;
delete conditions.$softRemove;
}
if (softRemove === false) {
return Model.remove.apply(this, arguments);
}
this.update(conditions, {
$set: {
isRemoved: true,
removedAt: new Date()
}
}, cb);
});
schema.static('restore', function(conditions, cb) {
conditions.isRemoved = true;
this.update(conditions, {
$set : { isRemoved: false },
$unset : { removedAt: 1 }
}, cb);
});
schema.method('remove', function(cb) {
this.isRemoved = true;
this.removedAt = new Date();
this.save(cb);
});
schema.method('restore', function(cb) {
this.isRemoved = false;
this.removedAt = undefined;
this.save(cb);
});
var setIsRemoved = function(next) {
if (this._conditions.isRemoved === undefined) {
this._conditions.isRemoved = false;
}
next(null);
};
schema.pre('find' , setIsRemoved);
schema.pre('findOne' , setIsRemoved);
}
module.exports = softRemove;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment