5

upsert操作でレコードを更新するためだけに更新タイムスタンプを設定したい(そして新しいレコードのタイムスタンプを挿入したい) 。

self.model.update({Id: obj.Id}, obj, {upsert: true}, function(err){
    if (err) {
        return;
    }

    //...

});

とにかくこれを処理する方法はありますか?

おそらく使用できるpre.saveミドルウェアがありますが、現在の操作が挿入か更新かを判断する方法はありますか?

前もって感謝します!

4

4 に答える 4

4

自動的に行うことはできません。$set: { timestamp: Date.now() }アップサートを使用してそれを行うことができます。

これについて議論している mongoose bugtracker には、解決済みの問題があります

少し遅れましたが、誰かの役に立てば幸いです!

于 2013-09-07T14:55:40.370 に答える
0

事前保存フックを使用できます。使用できる .isNew や .isModified などのフラグがいくつかあります。

self.schema.pre('save', function (next) {

  if (this.isNew) {
    this.updated = Date.now();
  }
  return next();
}

作成日については、ObjectId からタイムスタンプを抽出できます

于 2013-02-04T20:13:10.537 に答える
0

これには 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 が更新されます。

于 2015-03-15T17:52:54.027 に答える
0

インサート用

db.test.insert({ts:new Date()})

アップサート用

db.test.update({"_id" : ObjectId("540815fa802a63ddca867bc0")},{$set:{ts:new Date()}},{upsert:1})
于 2014-09-04T07:34:47.343 に答える