-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (91 loc) · 2.12 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
module.exports = function(schema) {
schema.add({
archived: Boolean,
archivedAt: Date
});
// all mongoose queries are built using these five base queries
// therefore adding the `archived !== true` condition here, adds it to all queries
var queries = ['find', 'findOne', 'findOneAndUpdate', 'update', 'count'];
queries.forEach(function(query) {
schema.pre(query, function(next) {
// add pre query conditional so that archived documents are invisible
this.where({
archived: {
'$ne': true
}
});
next();
});
});
schema.statics.archive = function(first, second) {
var callback;
var conditions;
if (typeof first === 'function') {
callback = first;
conditions = {};
} else {
callback = second;
conditions = first;
}
if (typeof callback !== 'function') {
throw ('Wrong arguments!');
}
var update = {
archived: true,
archivedAt: new Date()
};
this.update(conditions, update, function(err, raw) {
if (err) {
return callback(err);
}
// `raw` is raw mongo output
callback(null, raw);
});
};
schema.methods.archive = function(first, second) {
var callback = typeof first === 'function' ? first : second;
if (typeof callback !== 'function') {
throw ('Wrong arguments!');
}
this.archived = true;
this.archivedAt = new Date();
this.save(callback);
};
schema.statics.unarchive = function(first, second) {
var callback;
var conditions;
if (typeof first === 'function') {
callback = first;
conditions = {};
} else {
callback = second;
conditions = first;
}
if (typeof callback !== 'function') {
throw ('Wrong arguments!');
}
var update = {
$unset: {
archived: 1,
archivedAt: 1
}
};
// TODO update with mongoose
this.collection.update(conditions, update, function(err, raw) {
if (err) {
return callback(err);
}
if (raw === 0) {
return callback('Wrong arguments!');
}
// `raw` is raw mongo output
callback(null, raw);
});
};
schema.methods.unarchive = function(callback) {
// unset
this.archived = undefined;
this.archivedAt = undefined;
this.save(callback);
};
};