【问题标题】:Mongoose operation field is 'find' when I do 'update', why?当我“更新”时,Mongoose 操作字段是“查找”,为什么?
【发布时间】:2016-07-03 18:33:21
【问题描述】:

不知道是不是和Mongoose本身或者MongoDB驱动有关。

这是交易。我想将创建/更新的字段添加到我的架构中。我知道 Mongoose 可以开箱即用,但我需要使用 Unix Timestamp 而不是 date 对象。为此,我添加了在 Github (link to plugin) 上找到的插件,并将字段类型更改为 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) {...});

this.op 将等于 'find',而不是 'update',因此 'updated' 字段不会被更改。

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

【问题讨论】:

标签: node.js mongodb mongoose mongoose-schema mongoose-plugins


【解决方案1】:

您可以放弃插件并使用建议的 code hereDate.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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多