简体   繁体   English

如何在 Mongoose.js 中检查前/后更新挂钩中的修改字段

[英]How to check modified fields in pre/post update hook in Mongoose.js

I need to know modified fields or if a specific field was modified in pre or post update hook in a Mongoose schema.我需要知道修改的字段,或者一个特定领域在之前之后更新钩修改的猫鼬架构。 I tried the following, but still unable to figure it out:我尝试了以下方法,但仍然无法弄清楚:

schema.post('update', function (doc) {
    //check modified fields or if the name field was modified and then update doc
});

I know maybe there is a method isModified like in pre save but I don't know how to do the same with update hooks.我知道也许有一种方法isModified就像pre save一样,但我不知道如何使用更新钩子做同样的事情。 Any suggestions will be appreciated.任何建议将不胜感激。

If you want to know what fields you are modifying, then you need to issue an update command by calling save :如果您想知道您正在修改哪些字段,那么您需要通过调用save发出更新命令:

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

This way pre-save hook will be invoked and you will be having access to:这样预保存钩子将被调用,你将可以访问:

Document.prototype.modifiedPaths()

because this in pre-save hook refers to the document:因为thispre-save hook 中是指文档:

TankSchema.pre('save', function (next) {
  // ...
  this.modifiedPaths();
  // ...
});

On the other hand, you will not be able to achieve the same result when issuing an update command by calling update :另一方面,通过调用update发出更新命令时,您将无法获得相同的结果:

Tank.update({ _id: id }, { $set: { size: 'large' }}, callback);

because when calling update , document hooks (eg pre-save , post-save ) are not being executed at all.因为在调用update文档挂钩(例如pre-savepost-save )根本没有被执行。 Instead, query hooks are being executed (eg pre-update , post-update ) in that case.相反,在这种情况下正在执行查询挂钩(例如pre-updatepost-update )。 And the issue with query hooks is that this inside of them does not reference the document, so this.modifiedPaths === undefined查询钩子的问题是它们里面的this没有引用文档,所以this.modifiedPaths === undefined

schema.post('update', function (doc) {
  // `this` refers to model.Query
  // `doc` refers to CommandResult 
});

try it:试试看:

 schema.post('update', function () {
     const modifiedFields = this.getUpdate().$set;
     // ...
 });

There is no direct way of doing it.没有直接的方法可以做到。 There is a variable called isNew which is being tracked by mongoose to check if a new document is created. mongoose 正在跟踪一个名为 isNew 的变量,以检查是否创建了新文档。

see Document#isNew for information on Document#isNew有关Document#isNew的信息,请参阅 Document#isNew

However, you can created your own tracker to check in post save hook to identify wether document is updated or not.但是,您可以创建自己的跟踪器来检查保存后挂钩以识别文档是否更新。

schema.pre('save', function (doc) {
    this.isDocUpdated = false;
    if (this.isModified()) {
        this.isDocUpdated = true;
    }
});

schema.post('save', function (doc) {
    if (this.isDocUpdated) {
        console.log('post save hook called');
    }
});

For post()对于post()

Schema.post('update', function () {
        const modifiedFields = this.getUpdate().$set;
        console.log(modifiedFields);
});

For pre()对于pre()

schema.pre('update', function () {
        const modifiedFields = this.getUpdate();
        delete modifiedFields['$set'];
        delete modifiedFields['$setOnInsert'];
        console.log(modifiedFields);
});

Have a look at:看看:

http://mongoosejs.com/docs/api.html#document_Document-modifiedPaths http://mongoosejs.com/docs/api.html#document_Document-modifiedPaths

Returns an array of paths modified.返回修改过的路径数组。

  schema.pre('save', function (next) {
    //check modified fields or if the name field was modified and then update doc
    var modified_paths = this.modifiedPaths();
    next();
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM