admin管理员组

文章数量:1401669

I tried to @InjectModel to another service, but I got error:

UnknownDependenciesException [Error]: Nest can't resolve dependencies of the CustomerService (?). Please make sure that the argument "ProductModel" at index [0] is available in the GlobalModule context.

// app.module.ts
import {
  MiddlewareConsumer,
  Module,
  NestModule,
  RequestMethod,
} from '@nestjs/common';
import { CustomerModule } from './customer/customer.module';
import { CatsModule } from './cats/cats.module';
import {
  GlobalConfigModule,
  GlobalJwtModule,
  GlobalModule,
  GlobalMongooseModule,
} from './global/global.module';
import { Middleware3 } from './$middleware/middleware3';
import { ProductModule } from './product/product.module';
import middleware1 from './$middleware/middleware1';
@Module({
  imports: [
    GlobalModule,
    GlobalMongooseModule,
    GlobalConfigModule,
    GlobalJwtModule,
    CustomerModule,
    CatsModule,
    ProductModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(middleware1, Middleware3).exclude('customers').forRoutes({
      method: RequestMethod.GET,
      path: 'customer',
    });
  }
}
// product.module.ts

import { Module } from '@nestjs/common';
import { ProductService } from './product.service';
import { ProductController } from './product.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { Product, ProductSchema } from './product.schema';

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: Product.name,
        schema: ProductSchema,
      },
    ]),
  ],
  controllers: [ProductController],
  providers: [ProductService],
  exports: [MongooseModule, ProductService], // <-- already export the MongooseModule and ProductService Here
})
export class ProductModule {}
// customer.module.ts

@Module({
  imports: [ProductModule], // <-- import the ProductModule here
  controllers: [CustomerController],
  providers: [],
})
export class CustomerModule {}
// customer.service.ts

@Injectable()
export class CustomerService {
  constructor(
    @InjectModel(Product.name)
    private ProductModel: Model<Product>, // <-- try to inject the model here
  ) {}
  customers: CustomerDto[] = [];

  getAllCustomers() {
    return this.customers;
  }
  createCustomer(customer: CustomerDto) {
    this.customers.push(customer);
    return customer;
  }
}

I searched the internet and usually the problem is fixed by exporting the MongooseModule and the ProductService, but it doesn't works for me.

本文标签: typescriptNestJS InjectModel throw error when MongooseModule and the Service is exportedStack Overflow