如何在猫鼬中更新文档后添加一些操作

How to add some action after document update in mongoose

本文关键字:添加 操作 文档 更新      更新时间:2023-09-26

>例如,我有字段lastModified,当对象被修改时,此字段应使用当前日期更新。我怎样才能用猫鼬.js做到这一点?
架构示例:

var schema = new Schema({
    someFieldForUpdates: {
        type: String,
    },
    //when 1st field changed this one should be updated too
    lastModified: {
        type: Date,
        default: Date.now()
    }
});

我认为可以使用中间件来完成,例如保存后或保存前http://mongoosejs.com/docs/middleware.html

schema.post('save', function (doc) {
  console.log('%s has been saved', doc._id);
  // update another field 
})