You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS的useFactory中使用其他Mongoose模型?

在@nestjs/mongoose的pre-save钩子中使用其他模型执行查询

我懂你想在Post模型的pre('save')钩子里调用其他模型(比如User)做查询,但直接引用模型实例会碰到依赖没初始化的问题。下面给你两种靠谱的解决方案:

方法一:通过Mongoose上下文获取模型

在pre钩子的回调里,this指向当前的文档实例,你可以借助this.constructor.model()拿到其他模型的引用,不用额外做注入配置,简单直接:

MongooseModule.forFeatureAsync([
  {
    name: Post.name,
    useFactory: () => {
      // 重点:这里必须用普通function,不能用箭头函数,不然this会丢失文档上下文
      PostSchema.pre('save', async function() {
        // 通过当前模型的constructor获取User模型
        const UserModel = this.constructor.model('User');
        // 执行你的查询逻辑,比如根据帖子的authorId查用户
        const author = await UserModel.findOne({ _id: this.authorId });
        console.log('当前帖子的作者信息:', author);
        console.log('Hello from pre save');
      });
      return PostSchema;
    },
  },
]),

方法二:通过NestJS依赖注入注入模型

如果更习惯NestJS的依赖注入风格,可以在forFeatureAsync里显式注入目标模型,再在钩子中使用:

MongooseModule.forFeatureAsync([
  {
    name: Post.name,
    // 先导入User模型的配置,确保当前模块能访问到它
    imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
    useFactory: (userModel: Model<UserDocument>) => {
      PostSchema.pre('save', async function() {
        // 直接用注入好的userModel执行查询
        const author = await userModel.findOne({ _id: this.authorId });
        console.log('当前帖子的作者信息:', author);
        console.log('Hello from pre save');
      });
      return PostSchema;
    },
    // 指定要注入的模型token,和User模型的name对应
    inject: [getModelToken(User.name)],
  },
]),

几个关键提醒:

  • 别用箭头函数:pre钩子的回调必须是普通function,这样this才能指向当前的Post文档实例,拿到正确的上下文数据。
  • 异步操作要加async/await:如果你的查询是异步的(比如findOne),一定要用async/await包裹,确保钩子等查询完成后再继续执行保存流程。
  • 模型名称要对应:不管是this.constructor.model('User')还是getModelToken(User.name),里面的名称必须和你定义User模型时的name属性完全一致。

内容的提问来源于stack exchange,提问作者keval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:34:05