在不同的服务中共享 MongoModule

Share MongoModule in different services

我尝试在不同的 nestjs 服务中从我的 mongodb 获取用户数据。

我的 userModule 被标记为 @Global

@Global()
@Module({
  imports: [
    MongooseModule.forFeature([ { name: 'User', schema: UserSchema } ]),
    PassportModule,
    JwtModule.registerAsync({
      useFactory: () => ({
        secret: process.env.JWT_SECRET,
        signOptions: { expiresIn: '15m' },
      }),
    }),
  ],
  providers: [ UserResolver, UserService, JwtStrategy ],
  exports: [ UserService ],
})
export class UserModule {}
@Module({
  imports: [
    MongooseModule.forFeature([
      { name: 'Example', schema: ExampleSchema },
    ]),
  ],
  providers: [ ExampleService, ExampleResolver ],
})
export class ExampleModule {}

我尝试通过上下文中的 ID 加载用户。我将用户模型注入构造函数

例如,我有一个设置服务

import { Model } from 'mongoose'
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
...
@Injectable()
export class ExampleService {
  constructor (
    @InjectModel('Example') private readonly ExampleModel: Model<ExampleDocument>,
    @InjectModel('User') private readonly UserModel: Model<UserDocument>,
  ) {}

  async create ({ ctx, data }: { ctx: Ctx, data: ExampleCreateInput }): Promise<Example> {
    const user = await this.userModel.findById(ctx.user._id)

我的控制台出现以下错误,但由于 @Global,它应该已经导入了。当我尝试手动导入时,问题仍然存在。

app_1            | Potential solutions:
app_1            | - If UserModel is a provider, is it part of the current PortfolioModule?
app_1            | - If UserModel is exported from a separate @Module, is that module imported within PortfolioModule?
app_1            |   @Module({
app_1            |     imports: [ /* the Module containing UserModel */ ]
app_1            |   })

在我的服务中添加 UserModule 的问题非常简单,我还需要在我的 ExampleModule 中的猫鼬导入中添加它。

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: 'Example', schema: ExampleSchema },
      { name: 'User', schema: UserSchema },
    ]),
  ],
  providers: [ ExampleService, ExampleResolver ],
})
export class ExampleModule {}

不是将 user 架构添加到 ExampleModule 中的 MongooseModule,而是将 MongooseModule 添加到 exports of the UserModule` 和利用 module re-exporting.

但我认为,您应该改为从 UserModule 中导出 UserService,而不是为用户创建另一个连接点猫鼬文档,更接近领域驱动设计。您有一项服务可以为您与 table 对话。您在其他服务中使用该服务来获得访问权限,而无需直接公开 table,这就像我们编写 API 端点而不是让人们直接从数据库读取和写入的原因:控制和一致性。使用服务可以让 UserSchema 的所有代码保持一致,并以相同的方式进行验证。但同样,这就是我的全部意见。