[Mongoose] timestamp options で createdAt だけ使う

Mongoose の timestamp options で createdAt だけ使う方法を調べたけど、自分で pre hook に実装するしかなかったというお話です。

mongoose | マングース

options.timestamps では createdAt, updatedAt どちらも有効になる

まず、Mongoose version 4.8.5 時点では、ソースコードを読んだ限りでは options.timestamps には createdAt, updatedAt のどちらかだけ使うという option はありませんでした。

以下、Mongoose のソースコードを一部抜粋しました。

/**
 * Setup updatedAt and createdAt timestamps to documents if enabled
 *
 * @param {Boolean|Object} timestamps timestamps options
 * @api private
 */
Schema.prototype.setupTimestamp = function(timestamps) {
  if (timestamps) {
    var createdAt = timestamps.createdAt || 'createdAt';
    var updatedAt = timestamps.updatedAt || 'updatedAt';
// ...
  }
};

createdAt だけ有効にするサンプルコード

というわけで .pre(“save”) .pre(“findOneAndUpdate”) .pre(“update”) とかに options.timestamps 的な hook を追加するサンプルコードをご紹介します。

var yourSchema = new Schema({
  createdAt: {
    type: Date
  }
});
 
yourSchema.pre("save", function(next) {
  var now = new Date;
  if (this.isNew) {
    this.createdAt = now;
  }
  return next();
});
 
yourSchema.pre("findOneAndUpdate", function(next) {
  var now = new Date;
  this.findOneAndUpdate({}, {
    $setOnInsert: {
      createdAt: now
    }
  });
  return next();
});
 
yourSchema.pre("update", function(next) {
  var now = new Date;
  this.update({}, {
    $setOnInsert: {
      createdAt: now
    }
  });
  return next();
});

最後に、小ネタですが timestamp options を削除するという issue があるので確認してみると version 4.11 のマイルストーンで削除されるかもしれません。