Created
August 14, 2015 09:15
-
-
Save RobertWHurst/aee50ec21bc49ce345fa to your computer and use it in GitHub Desktop.
Mongoose Soft Remove Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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