根据猫鼬关于中间件这里的文档
下面的模型和查询函数支持查询中间件。在查询中间件功能中,这是指查询。
这意味着我可以编写像下面这样的中间件,只要调用findOneAndUpdate方法,它就会执行:
mySchema.pre('findOneAndUpdate', function(next){
const query = this
console.log("called the pre-findOneAndUpdate middleware and hello");
})现在,如果我想让上面的console.log在pre('count')、pre('replaceOne')、pre('findOneAndRemove')...etc上打印它的输出,我将不得不写得太多了。
是否有办法这样做:
mySchema.pre('*', function(next){
const query = this
console.log("called the pre-* middleware and hello");
})其中*指引号中长列表中列出的任何方法
??
发布于 2022-07-03 17:38:50
看来没有这样的可能
您可以动态地构造它。
您可以在这里获取一个方法列表:https://github.com/Automattic/mongoose/blob/c5893fa9f6d652d2bed08a52ad58f0f875e34bb4/lib/helpers/query/validOps.js
(我在图书馆里找不到)
然后传递该数组,或使用循环构造每个方法:
// https://github.com/Automattic/mongoose/blob/c5893fa9f6d652d2bed08a52ad58f0f875e34bb4/lib/helpers/query/validOps.js
const validOps = [
// Read
'count',
'countDocuments',
'distinct',
'estimatedDocumentCount',
'find',
'findOne',
// Update
'findOneAndReplace',
'findOneAndUpdate',
'replaceOne',
'update',
'updateMany',
'updateOne',
// Delete
'deleteMany',
'deleteOne',
'findOneAndDelete',
'findOneAndRemove',
'remove'
]
mySchema.pre(validOps, function(next) {
//...
})
// or
for (const method of validOps) {
mySchema.pre(method, function(next) {
const query = this;
console.log(`called the pre-${method} middleware and hello`);
})
}https://stackoverflow.com/questions/72846521
复制相似问题