Created
February 13, 2016 16:03
-
-
Save TonyPythoneer/1c8a59c4a02dfa75248f to your computer and use it in GitHub Desktop.
mongoose 自动生成数据的创建时间和跟新时间
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Timestamps 用于自动产生数据的创建时间和更新时间 | |
* | |
* 使用方法: | |
* | |
* schema.plugin(require('./timestamp')); | |
* | |
*/ | |
var timestampsPlugin = function (schema) { | |
if (schema.path('_id')) { | |
schema.add({ | |
updated_at: Date | |
}); | |
schema.virtual('created_at').get( function () { | |
if (this._created_at) { | |
return this._created_at; | |
} | |
this._created_at = this._id.getTimestamp(); | |
return this._created_at; | |
}); | |
schema.pre('save', function (next) { | |
if (this.isNew) { | |
this.updated_at = this.created_at; | |
} else { | |
this.updated_at = new Date(); | |
} | |
next(); | |
}); | |
} else { | |
schema.add({ | |
created_at: Date, | |
updated_at: Date | |
}); | |
schema.pre('save', function (next) { | |
if (!this.created_at) { | |
this.created_at = this.updated_at = new Date(); | |
} else { | |
this.updated_at = new Date(); | |
} | |
next(); | |
}); | |
} | |
} | |
exports = module.exports = timestampsPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment