tellform/app/libs/timestamp.server.plugin.js

37 lines
964 B
JavaScript
Raw Normal View History

2017-10-11 05:07:13 +00:00
'use strict';
// Plugin
module.exports = function timestamp (schema, options) {
options = options || (options === {});
2017-10-11 05:07:13 +00:00
// Options
var fields = {},
createdPath = options.createdPath || 'created',
modifiedPath = options.modifiedPath || 'modified',
useVirtual = (options.useVirtual !== undefined) ? options.useVirtual : true;
2017-10-11 05:07:13 +00:00
// Add paths to schema if not present
if (!schema.paths[createdPath]) {
fields[modifiedPath] = { type: Date };
2017-10-11 05:07:13 +00:00
}
if (useVirtual) {
// Use the ObjectID for extracting the created time
schema.virtual(createdPath).get(function () {
return new Date(this._id.generationTime * 1000);
});
2017-10-11 05:07:13 +00:00
} else {
if (!schema.paths[createdPath]) {
fields[createdPath] = {
type: Date,
default: Date.now
};
2017-10-11 05:07:13 +00:00
}
}
schema.add(fields);
2017-10-11 05:07:13 +00:00
// Update the modified timestamp on save
schema.pre('save', function (next) {
this[modifiedPath] = new Date();
next();
});
};