【问题标题】:How to reference Mongoose model in different NestJS module如何在不同的 NestJS 模块中引用 Mongoose 模型
【发布时间】:2020-02-26 00:19:27
【问题描述】:

我是 NestJS 的新手。我确信这是一个简单的问题,但我就是找不到答案。

nest docs 中建议每个模型有一个模块。这涉及使用MongooseModule.forFeature 创建模型:

imports: [MongooseModule.forFeature([{ name: 'Cat', schema: CatSchema }])]

文档说:

如果您还想在另一个模块中使用模型,请将 MongooseModule 添加到 CatsModuleexports 部分并在另一个模块中导入 CatsModule

我的问题是如何在新模块中引用模型。

我可以看到:

  1. How this would be done 如果模型是使用 mongoose.model('Name', MySchema) 创建的
  2. What exports are needed
  3. A question 暗示这将使用 import { Model } from 'mongoose'; @InjectModel('name') myModel: Model<MyInterface>) 完成,但感觉就像它重复了 MongooseModule.forFeature 完成的模型创建,因为它再次将 mongoose 模型与模式结合起来

任何帮助表示赞赏!

【问题讨论】:

    标签: node.js mongoose nestjs


    【解决方案1】:

    所以我认为方法3是正确的。

    根据@silvelo 的this comment,您在注入模式时必须单独提供集合名称和接口(而不是模式本身):

    @Module({
      imports: [
        MongooseModule.forFeature([
          { name: GAME_COLLECTION_NAME, schema: GameSchema },
        ]),
      ],
      controllers: [GamesController],
      components: [GamesService],
      exports: [GamesService, MongooseModule],
    })
    export class GamesModule implements NestModule {}
    
    @Module({
      imports: [
        MongooseModule.forFeature([
          { name: USER_COLLECTION_NAME, schema: UserSchema },
        ]),
        GamesModule,
        LinksModule,
      ],
      controllers: [UsersController],
      components: [UsersService],
      exports: [UsersService],
    })
    export class UsersModule implements NestModule {}
    
    @Component()
    export class UsersService {
      constructor(
        @InjectModel(GAME_COLLECTION_NAME) private readonly gameModel: Model<Game>,
        @InjectModel(USER_COLLECTION_NAME) private readonly userModel: Model<User>,
      ) {}
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2020-10-02
      • 2020-07-16
      • 2020-05-25
      • 2020-06-16
      • 1970-01-01
      • 2021-10-16
      • 2020-09-29
      • 2020-10-17
      相关资源
      最近更新 更多