Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,17 @@ function timestampsPlugin(schema, options) {
dataObj[updatedAt] = updatedAtOpts;
}

if (schema.path(createdAt)) {
if (!schema.path(updatedAt) && updatedAt) {
schema.add(dataObj);
}
if (schema.virtual(createdAt).get) {
schema.virtual(createdAt)
.get( function () {
if (this["_" + createdAt]) return this["_" + createdAt];
return this["_" + createdAt] = this._id.getTimestamp();
});
}
function setupCreatedVirtual(){
schema.virtual(createdAt)
.get( function () {
if (this["_" + createdAt]) return this["_" + createdAt];
return this["_" + createdAt] = this._id.getTimestamp();
});
}

function setupPreSave(condition,createdAt){
schema.pre('save', function(next) {
if (this.isNew) {
if (condition(this)) {
var newDate = new Date;
if (createdAt) this[createdAt] = newDate;
if (updatedAt) this[updatedAt] = newDate;
Expand All @@ -61,24 +59,25 @@ function timestampsPlugin(schema, options) {
}
next();
});
}

} else {
if (createdAt) {
dataObj[createdAt] = createdAtOpts;
if (schema.path(createdAt)) {
if (!schema.path(updatedAt) && updatedAt) {
schema.add(dataObj);
}
if (dataObj[createdAt] || dataObj[updatedAt]) {

if (schema.virtual(createdAt).get) {
setupCreatedVirtual();
}

setupPreSave(function(that){return that.isNew; },createdAt); //Also update createdAt

} else {
if (dataObj[updatedAt]) {
schema.add(dataObj);
}
schema.pre('save', function(next) {
if (!this[createdAt]) {
var newDate = new Date;
if (createdAt) this[createdAt] = newDate;
if (updatedAt) this[updatedAt] = newDate;
} else if (this.isModified() && updatedAt) {
this[updatedAt] = new Date;
}
next();
});
setupPreSave(function(that){return !that[createdAt]; }); //do not create createdAt in db, so undefined in second parameter
setupCreatedVirtual();
}

schema.pre('findOneAndUpdate', function(next) {
Expand Down