【问题标题】:Mongoose hooks via regEx not getting triggered通过正则表达式的猫鼬钩子没有被触发
【发布时间】:2021-06-05 01:00:12
【问题描述】:

当对我的 mongo 集合执行查询时,我正在尝试调用某些钩子。


DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"a@gmail.com"},function(err,doc){
  if(err||!doc){
    return console.log("no such document found!!!!!!!",err,doc)
  }
})

在执行上述查询时,基于正则表达式的钩子永远不会被触发,而那些将字符串作为输入参数的钩子工作正常。 参考:mongoose docs for hooks


//never triggered
DispatchRequest.post(/^find/, async function () {
  console.log("FIND HOOK POST  IS CALLED") 
});

//never triggered
DispatchRequest.pre(/^find/, function (next) {
  console.log("FIND HOOK PRE  IS CALLED")
});

//works fine
DispatchRequest.post("findOneAndUpdate", async function () {
  console.log("findOneAndUpdate  IS CALLED post", docToUpdate?.email)
});

//works fine
DispatchRequest.pre("findOneAndUpdate", async function () {
  console.log("findOneAndUpdate  IS CALLED pre", docToUpdate?.email)
});
});

猫鼬版本:5.0.3

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    它不起作用,因为您使用的是稍微过时的 Mongoose 版本。 5.3 版中添加了正则表达式支持。查看更新日志here

    feat(schema): 支持 schema.pre(RegExp, fn) 和 schema.post(RegExp, fn) #6680

    您需要将您的 Mongoose 更新到较新的版本 (5.3+) 或保留旧版本,但列出您想要挂钩的所有 find 方法。

    【讨论】:

    • 我有 mongoose 6.1.4 版,但仍然无法正常工作
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    相关资源
    最近更新 更多