猫鼬操作字段在我进行"更新"时'find',为什么?


我不知道

这是否与Mongoose本身或MongoDB驱动程序有关。

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

我在插件源代码中找到了这些行:

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) {...});

this.op 将等于"查找",而不是"更新",因此"更新"字段不会更改。

我不明白为什么会这样,为什么操作是"查找"而不是"更新"。我试图搜索猫鼬源代码,但目前我还没有找到答案。

你可以放弃插件,将这里提出的代码与Date.now()(now()返回一个Unix时间戳一起使用):

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();
});

相关内容

最新更新