これには mongoose プラグインがあります。 ( Mongoose Timestamps Plugin )
ここに CoffeeScript の実装があります - 必要に応じて js2coffe.com を使用して js に変換してください。
これはすべてのモデルで使用できます。
以下のように関数を作成します
# * Mongoose Timestamps Plugin
# * Copyright(c) 2012 Nicholas Penree <nick@penree.com>
# * Original work Copyright(c) 2012 Brian Noguchi
# * Modified from Fino 2014
# * MIT Licensed
#
timestamps = (schema, options) ->
updated_at = "updated_at"
created_at = "created_at"
updatedAtType = Date
createdAtType = Date
if typeof options is "object"
if typeof options.updated_at is "string"
updated_at = options.updated_at
else if typeof options.updated_at is "object"
updated_at = options.updated_at.name or updated_at
updatedAtType = options.updated_at.type or updatedAtType
if typeof options.created_at is "string"
created_at = options.created_at
else if typeof options.created_at is "object"
created_at = options.created_at.name or created_at
createdAtType = options.created_at.type or createdAtType
dataObj = {}
dataObj[updated_at] = updatedAtType
if schema.path("created_at")
schema.add dataObj
schema.virtual(created_at).get ->
this["_" + created_at] if this["_" + created_at]
return this["_" + created_at] = @_id.getTimestamp()
schema.pre "save", (next) ->
if @isNew
this[updated_at] = this[created_at]
else
this[updated_at] = new Date
next()
return
else
dataObj[created_at] = createdAtType
schema.add dataObj
schema.pre "save", (next) ->
unless this[created_at]
this[created_at] = this[updated_at] = new Date
else
this[updated_at] = new Date
next()
return
return
次に、Mongoose モデルで次の操作を行います
userSchema.plugin タイムスタンプ
それでおしまい!
これにより、created_at が追加され、「model.save()」を使用し続けると update_at が更新されます。