我需要知道修改过的字段,或者特定字段是否在 Mongoose 架构中的 pre 或 post update 钩子(Hook)中被修改。 我尝试了以下方法,但仍然无法弄清楚:
schema.post('update', function (doc) {
//check modified fields or if the name field was modified and then update doc
});
我知道也许有一个方法 isModified 就像在 pre save 但我不知道如何用 更新 Hook 。 任何建议将不胜感激。
最佳答案
如果您想知道正在修改哪些字段,则需要通过调用 save
发出一个update 命令:
Tank.findById(id, function (err, tank) {
if (err) return handleError(err);
tank.set({ size: 'large' });
tank.save(function (err, updatedTank) {
if (err) return handleError(err);
res.send(updatedTank);
});
});
这样预保存 Hook 将被调用,您将可以访问:
Document.prototype.modifiedPaths()
因为 pre-save Hook 中的 this
引用了文档:
TankSchema.pre('save', function (next) {
// ...
this.modifiedPaths();
// ...
});
另一方面,通过调用 update
发出 update 命令将无法获得相同的结果:
Tank.update({ _id: id }, { $set: { size: 'large' }}, callback);
因为在调用 update
时,文档 Hook (例如 pre-save、post-save)不是完全被处决。相反,在这种情况下,查询 Hook 正在执行(例如更新前、更新后)。 query hooks 的问题是它们里面的 this
没有引用文档,所以 this.modifiedPaths === undefined
schema.post('update', function (doc) {
// `this` refers to model.Query
// `doc` refers to CommandResult
});
关于javascript - 如何在 Mongoose.js 中检查更新前/更新后 Hook 中的修改字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46589715/