-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
59 lines (48 loc) · 1.94 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
49
50
51
52
53
54
55
56
57
58
59
var Model = require('mongoose').Model;
module.exports = function MongooseParanoidPlugin(schema, options = {}) {
if (schema.options.paranoid !== true) {
return; // skip overriding native methods if paranoid is not enabled explicitly
}
var field = options.field || 'deletedAt';
schema.add({
[field]: {
type: Date
}
});
['find', 'findOne', 'updateOne', 'count', 'update'].forEach(function (method) {
schema.static(method, function () {
var args = Array.from(arguments);
var isParanoidManuallyDisabled = args && args[2] && args[2].paranoid === false;
if (this.isParanoidDisabled || isParanoidManuallyDisabled) {
return Model[method].apply(this, arguments);
}
return Model[method].apply(this, arguments).where(field).exists(false);
});
});
schema.static('restore', function (conditions, options, callback) {
options.paranoid = false;
return this.update(conditions, {
$unset: { [field]: '' },
}, options, callback);
});
['deleteMany', 'deleteOne', 'remove'].forEach(function(method) {
schema.static(method, function(conditions, options, callback) {
if (options && typeof options === 'function') {
callback = options;
}
var isParanoidManuallyDisabled = options && options.paranoid === false;
if (this.isParanoidDisabled || isParanoidManuallyDisabled) {
return Model[method].apply(this, [conditions, callback]);
}
if (method === 'deleteMany') {
return this.updateMany(conditions, {
[field]: new Date()
}, options, callback)
} else {
return this.updateOne(conditions, {
[field]: new Date()
}, options, callback)
}
});
});
};