Skip to content

Instantly share code, notes, and snippets.

@TonyPythoneer
Created February 13, 2016 16:03
Show Gist options
  • Save TonyPythoneer/1c8a59c4a02dfa75248f to your computer and use it in GitHub Desktop.
Save TonyPythoneer/1c8a59c4a02dfa75248f to your computer and use it in GitHub Desktop.
mongoose 自动生成数据的创建时间和跟新时间
/**
* 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