forked from fzaninotto/uptime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycleEventsPlugin.js
More file actions
49 lines (49 loc) · 1.54 KB
/
lifecycleEventsPlugin.js
File metadata and controls
49 lines (49 loc) · 1.54 KB
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
/**
* Mongoose plugin adding lifecyle events on the model class.
*
* Initialization is straightforward:
*
* var lifecycleEventsPlugin = require('path/to/lifecycleEventsPlugin');
* var Book = new Schema({ ... });
* Book.plugin(lifecycleEventsPlugin);
*
* Now the model emits lifecycle events before and after persistence operations:
*
* - preInsert
* - postInsert
* - preUpdate
* - postUpdate
* - preSave (called for both inserts and updates)
* - postSave (called for both inserts and updates)
* - preRemove
* - postRemove
*
* You can listen to these events directly on the model.
*
* var Book = require('path/to/models/book');
* Book.on('preInsert', function(book) {
* // do stuff...
* });
*/
module.exports = exports = function lifecycleEventsPlugin(schema) {
schema.pre('save', function (next) {
var model = this.model(this.constructor.modelName);
model.emit('preSave', this);
this.isNew ? model.emit('preInsert', this) : model.emit('preUpdate', this);
this._isNew_internal = this.isNew;
next();
});
schema.post('save', function() {
var model = this.model(this.constructor.modelName);
model.emit('postSave', this);
this._isNew_internal ? model.emit('postInsert', this) : model.emit('postUpdate', this);
this._isNew_internal = undefined;
});
schema.pre('remove', function (next) {
this.model(this.constructor.modelName).emit('preRemove', this);
next();
});
schema.post('remove', function() {
this.model(this.constructor.modelName).emit('postRemove', this);
});
};