如何在 mongoose 中更新 pre 或 post 查询挂钩上的文档?

How to update document on pre or post query hook in mongoose?

我正在尝试更新查询挂钩上的字段。例如:

var mySchema = new Schema({
  name: String,
  queryCount: {type: Number, default:0}
});

我想增加和更新每个 findfindOne 查询的 queryCount 字段。

mySchema.post('find', function (doc) {
  // here is the magic
});

我已经尝试了一些东西,但到目前为止没有成功。我可以在模型中实现还是必须在控制器中实现?

你要的是post init hook

mySchema.post('init', function (doc) {
  doc.queryCount++;
  doc.save();
});

或者,您可以使用在内部调用 findAndUpdate()

的 mongoose 静态方法
mySchema.statics.findWithIncrement = function (query, callback) {

    this.findAndUpdate(query, { $inc: { queryCount: 1 })
        .exec(function(err, res) {

            if (err) return callback(err);

            //Handle response
        });
}

然后在你的控制器中使用方法:

MyModel.findWithIncrement({name: "someName"}, function (err, result) {

})