Node.js 猫鼬操作字段为';查找';当我这样做时';更新';,为什么?

Node.js 猫鼬操作字段为';查找';当我这样做时';更新';,为什么?,node.js,mongodb,mongoose,mongoose-schema,mongoose-plugins,Node.js,Mongodb,Mongoose,Mongoose Schema,Mongoose Plugins,我不知道这是否与Mongoose本身或MongoDB驱动程序有关 这是交易。我想将创建/更新的字段添加到我的架构中。我知道Mongoose可以开箱即用,但我需要使用Unix时间戳而不是date对象。为了实现这一点,我添加了在Github()上找到的插件,并将字段类型更改为Number以存储时间戳 我在插件源代码中发现了以下几行代码: schema.pre('update', function(next) { if (this.op === 'update') { this

我不知道这是否与Mongoose本身或MongoDB驱动程序有关

这是交易。我想将创建/更新的字段添加到我的架构中。我知道Mongoose可以开箱即用,但我需要使用Unix时间戳而不是date对象。为了实现这一点,我添加了在Github()上找到的插件,并将字段类型更改为Number以存储时间戳

我在插件源代码中发现了以下几行代码:

schema.pre('update', function(next) {
    if (this.op === 'update') {
        this._update = this._update || {};
        this._update[updatedAt] = new Date().getTime;
        this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
        this._update['$setOnInsert'][createdAt] = new Date().getTime;
    }
    next();
    });
如果我这样做

MyAwesomeModel.update(...., function (e, d) {...});
此.op将等于“查找”,而不是“更新”,因此不会更改中的“更新”字段

我不明白为什么会这样,为什么操作是“查找”而不是“更新”。
我试图通过mongoose源代码进行搜索,但到目前为止我还没有找到答案。

您可以放弃该插件,使用建议的with(now()返回Unix时间戳):


更新会定期调用mongo驱动程序。Schema.update通过设计绕过中间件。因此,
.pre
不能与
更新一起使用。您可以获得更多详细信息:
var ItemSchema = new Schema({
    name        : { type: String, required: true, trim: true },
    created_at  : { type: Number },
    updated_at  : { type: Number }
});

ItemSchema.pre('save', function(next){
  now = Date.now();
  this.updated_at = now;
  if ( !this.created_at ) {
    this.created_at = now;
  }
  next();
});