代码之家  ›  专栏  ›  技术社区  ›  Berlin Johns. M

Nest.js“Nest无法解析依赖项”错误

  •  0
  • Berlin Johns. M  · 技术社区  · 1 年前

    学习nest.js时 我得到了以下依赖项在我的nest.js API中出错,我试图用很多方法调试代码,但这对我没有帮助!

      [Nest] 21172  - 09/12/2023, 10:16:19 am   ERROR [ExceptionHandler] Nest can't resolve dependencies of the ProductService (?). Please make sure that the argument ProductsModel at index [0] is available in the ProductModule context.
    
    Potential solutions:
    - Is ProductModule a valid NestJS module?
    - If ProductsModel is a provider, is it part of the current ProductModule?
    - If ProductsModel is exported from a separate @Module, is that module imported within ProductModule?
      @Module({
        imports: [ /* the Module containing ProductsModel */ ]
      })
    
    Error: Nest can't resolve dependencies of the ProductService (?). Please make sure that the argument ProductsModel at index [0] is available in the ProductModule context.
    
    Potential solutions:
    - Is ProductModule a valid NestJS module?
    - If ProductsModel is a provider, is it part of the current ProductModule?
    - If ProductsModel is exported from a separate @Module, is that module imported within ProductModule?
      @Module({
        imports: [ /* the Module containing ProductsModel */ ]
      })
    

    我提供了下面的源代码! 产品服务:

    import { Injectable, NotFoundException } from '@nestjs/common';
    
    
    
    
    import mongoose from 'mongoose';
    import { Products } from './schemas/product.schema';
    import { InjectModel } from '@nestjs/mongoose';
    import { Query  } from 'express-serve-static-core';
    import { CreateProductDto } from './dto/create-product.dto';
    
    
    @Injectable()
    export class ProductService {
       
        constructor(
            @InjectModel(Products.name)
            private productModel:mongoose.Model<Products>,
    
        ) {
        }
    
        async findAllProducts(query: Query): Promise<Products[]> {
            const resPerPage = 2
            const currentPage = Number(query.page) || 1
            const skip =resPerPage* (currentPage-1)
            const category = query.category ? {
              category: {
                $regex: query.category,
                $options:'i'
              }
            }:{}
            const serviceRequestes = await this.productModel.find({ ...category }).limit(resPerPage).skip(skip);
            return serviceRequestes;
          }
        
          async createProduct(request: Products): Promise<Products> {
            const Product = await this.productModel.create(request);
            return Product;
          }
        
          async findById(id: string): Promise<Products> {
            const Products = await this.productModel.findById(id);
            if (!Products) {
              throw new NotFoundException(
                'The Service Product with the given ID not Found',
              );
            }
            return Products;
          }
        
          async updateById(
            id: string,
            Products: Products,
          ): Promise<Products> {
            return await this.productModel.findByIdAndUpdate(
              id,
              Products,
              {
                new: true,
                runValidators: true,
              },
            );
          }
            
          async deleteById(
            id: string,
          ): Promise<Products> {
            return await  this.productModel.findByIdAndDelete(id)
          }
    }
    
    

    产品管理员:

    import {
      Body,
      Controller,
      Delete,
      Get,
      Param,
      Post,
      Put,
      Query,
    } from '@nestjs/common';
    import { ProductService } from '../product.service';
    import { Products } from '../schemas/product.schema';
    import { CreateProductDto } from '../dto/create-product.dto';
    import { UpdateProductDto } from '../dto/update-product.dto';
    import { Query as ExpressQuery } from 'express-serve-static-core';
    
    @Controller('products')
    export class ProductController {
      constructor(private productService: ProductService) {}
    
      @Get()
      async getAllProducts(@Query() query: ExpressQuery): Promise<Products[]> {
        return this.productService.findAllProducts(query);
      }
    
      @Get(':id')
      async getProductById(
        @Param('id')
        id:string,
      ): Promise<Products>{
        return this.productService.findById(id);
      };
    
      @Post('create')
      async createProduct(
        @Body()
        product: CreateProductDto,
      ): Promise<Products> {
        return this.productService.createProduct(product);
      }
    
      @Put(':id')
      async updateProduct(
        @Param('id')
        id: string,
        @Body()
        product: UpdateProductDto,
      ):Promise<Products> {
        return this.productService.updateById(id, product);
      }
    
      @Delete(':id')
      async deleteProduct(
        @Param(':id')
        id:string
      ): Promise<Products>{
        return this.productService.deleteById(id);
      }
      
    }
    
    

    产品模块:

    import { Module } from '@nestjs/common';
    import { ProductController } from './controller/product.controller';
    import { ProductService } from './product.service';
    import { MongooseModule } from '@nestjs/mongoose';
    import { productSchema } from './schemas/product.schema';
    @Module({
      imports: [MongooseModule.forFeature([{ name: 'product', schema: productSchema }])],
      controllers: [ProductController],
      providers: [ProductService],
    })
    export class ProductModule {}
    

    Nestjs版本详细信息:
    “@nestjs/common”:“^10.0.0”,
    “@nestjs/config”:“^3.1.1”,
    “@nestjs/core”:“^10.0.0”,

    请提供任何解决方案或建议!

    1 回复  |  直到 1 年前
        1
  •  0
  •   Ali Torki    1 年前

    你注射了

    @InjectModel(Products.name)
    

    但您没有在此处注册正确的型号

    MongooseModule.forFeature([{ name: 'product', schema: productSchema }])
    

    将其更改为:

    MongooseModule.forFeature([{ name: Products.name, schema: productSchema }])