forked from drudge/mongoose-timestamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
45 lines (42 loc) · 1.07 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
/*!
* Mongoose Timestamps Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* Original work Copyright(c) 2012 Brian Noguchi
* MIT Licensed
*/
var mongoose = require('mongoose');
var BinaryParser = require('mongoose/node_modules/mongodb/node_modules/bson').BinaryParser;
function timestampsPlugin(schema, options) {
if (schema.path('_id')) {
schema.add({
updatedAt: Date
});
schema.virtual('createdAt')
.get( function () {
if (this._createdAt) return this._createdAt;
return this._createdAt = this._id.getTimestamp();
});
schema.pre('save', function (next) {
if (this.isNew) {
this.updatedAt = this.createdAt;
} else {
this.updatedAt = new Date;
}
next();
});
} else {
schema.add({
createdAt: Date
, updatedAt: Date
});
schema.pre('save', function (next) {
if (!this.createdAt) {
this.createdAt = this.updatedAt = new Date;
} else {
this.updatedAt = new Date;
}
next();
});
}
}
module.exports = timestampsPlugin;