【问题标题】:NestJS/Mongoose - query inside hooksNestJS/Mongoose - 在钩子里面查询
【发布时间】:2021-05-03 20:06:53
【问题描述】:

我想从标题创建 slug 并执行查询以检查 slug 是否存在。我试图在保存功能的预挂钩中做到这一点,但我似乎找不到执行查询的方法。我找到了this 解决方案,但是当我尝试调用任何模式查询函数时,我收到以下错误:Property 'find' does not exist on type 'Function'.ts。

这只是我尝试运行的代码示例:

export const CodeBlockSchema = SchemaFactory.createForClass(CodeBlock);
CodeBlockSchema.pre('save', function (next) {
  this.slug = slugify(this.title.toLowerCase());
  const Item = this.constructor;
  Item.find({ name: this.title }).count().exec();
  next();
});

我的模块在另一个类中,我找到了一些导入模块的解决方案,但我是 Nestjs 的新手,不认为这是一个优雅的解决方案。是否可以在钩子中访问模式查询?

【问题讨论】:

    标签: node.js mongoose nestjs


    【解决方案1】:

    我得到了它的铸造:

    const codeBlockModule = <Model<CodeBlock>>this.constructor;
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2021-03-03
      • 2021-09-19
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2015-10-16
      • 2021-09-08
      相关资源
      最近更新 更多