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

时间:2015-03-08 04:16:33

标签: javascript mongoose

E.g。我有字段lastModified,当对象被修改时,该字段应该用当前日期更新。我怎么能用mongoose.js做这个呢? 架构示例:

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

1 个答案:

答案 0 :(得分:0)

我认为可以使用后期保存或预先存储等中间件来完成 http://mongoosejs.com/docs/middleware.html

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