forked from dsanel/mongoose-delete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (37 loc) · 1.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var Schema = require('mongoose').Schema;
module.exports = function (schema, options) {
schema.add({ deleted: Boolean });
if (options && options.deletedAt === true) {
schema.add({ deletedAt: { type: Date} });
}
if (options && options.deletedBy === true) {
schema.add({ deletedBy: Schema.Types.ObjectId });
}
schema.pre('save', function (next) {
if (!this.deleted) {
this.deleted = false;
}
next();
});
schema.methods.delete = function (first, second) {
var callback = typeof first === 'function' ? first : second,
deletedBy = second !== undefined ? first : null;
if (typeof callback !== 'function') {
throw ('Wrong arguments!');
}
this.deleted = true;
if (schema.path('deletedAt')) {
this.deletedAt = new Date();
}
if (schema.path('deletedBy')) {
this.deletedBy = deletedBy;
}
this.save(callback);
};
schema.methods.restore = function (callback) {
this.deleted = false;
this.deletedAt = undefined;
this.deletedBy = undefined;
this.save(callback);
};
};