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

问题描述 投票:0回答: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”,

任何解决方案或建议请!

node.js api dependency-injection nestjs
1个回答
0
投票

您已经注射了

@InjectModel(Products.name)

但是您没有在这里注册正确的型号

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

更改为:

MongooseModule.forFeature([{ name: Products.name, schema: productSchema }])
© www.soinside.com 2019 - 2024. All rights reserved.