forked from drudge/mongoose-timestamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (79 loc) · 2.43 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
/*!
* Mongoose Timestamps Plugin
* Copyright(c) 2012 Nicholas Penree <[email protected]>
* Original work Copyright(c) 2012 Brian Noguchi
* MIT Licensed
*/
function timestampsPlugin(schema, options) {
var updatedAt = 'updatedAt';
var createdAt = 'createdAt';
var updatedAtType = Date;
var createdAtType = Date;
if (typeof options === 'object') {
if (typeof options.updatedAt === 'string') {
updatedAt = options.updatedAt;
} else if (typeof options.updatedAt === 'object') {
updatedAt = options.updatedAt.name || updatedAt;
updatedAtType = options.updatedAt.type || updatedAtType;
}
if (typeof options.createdAt === 'string') {
createdAt = options.createdAt;
} else if (typeof options.createdAt === 'object') {
createdAt = options.createdAt.name || createdAt;
createdAtType = options.createdAt.type || createdAtType;
}
}
var dataObj = {};
dataObj[updatedAt] = updatedAtType;
if (schema.path(createdAt)) {
schema.add(dataObj);
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 if (this.isModified()) {
this[updatedAt] = new Date;
}
next();
});
} else {
dataObj[createdAt] = createdAtType;
schema.add(dataObj);
schema.pre('save', function (next) {
if (!this[createdAt]) {
this[createdAt] = this[updatedAt] = new Date;
} else if (this.isModified()) {
this[updatedAt] = new Date;
}
next();
});
}
schema.pre('findOneAndUpdate', function (next) {
if (this.op === 'findOneAndUpdate') {
this._update = this._update || {};
this._update[updatedAt] = new Date;
this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
this._update['$setOnInsert'][createdAt] = new Date;
}
next();
});
schema.pre('update', function(next) {
if (this.op === 'update') {
this._update = this._update || {};
this._update[updatedAt] = new Date;
this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
this._update['$setOnInsert'][createdAt] = new Date;
}
next();
});
if(!schema.methods.hasOwnProperty('touch'))
schema.methods.touch = function(callback){
this[updatedAt] = new Date;
this.save(callback)
}
}
module.exports = timestampsPlugin;