【发布时间】: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' 字段不会被更改。
我不明白为什么会这样,为什么操作是“查找”而不是“更新”。 我试图通过猫鼬源代码搜索,但到目前为止我还没有找到答案。
【问题讨论】:
-
Update 会定期调用 mongo 驱动程序。 Schema.update 设计绕过中间件。因此
.pre不适用于update。您可以获取更多详情:github.com/Automattic/mongoose/issues/2672
标签: node.js mongodb mongoose mongoose-schema mongoose-plugins