首页 > 解决方案 > 为什么它显示错误:CastError: Cast to ObjectId failed for value "$this.categoryId" at path "category" for model "Product"?

问题描述

我在后端使用nodejs和MongoDB来创建我的应用程序和前端的Angular。当我尝试从邮递员那里获取特定“类别”下的“产品”的价值时,邮递员会回复成功消息并传递值。但是当我尝试通过前端查看时,就会出现真正的问题。

一旦我尝试获取特定类别中的产品,它就会显示以下错误:

CastError: Cast to ObjectId failed for value "$this.categoryId" at path "category" for model "Product"
    at model.Query.exec

我已经检查了后端,它运行顺利,没有任何错误。我猜这个错误意味着“categoryId”参数没有获得有效值,但它不能是因为我的本地主机被重定向到单个 categoryId 链接http://localhost:4200/categories/5f004ae05ca53a0da8d5c043,但它无法在类别中加载产品。

这是我在 TypeScript 中编写代码的方式category.component.ts

import { Component, OnInit } from '@angular/core';

import { ActivatedRoute } from '@angular/router' ;
import { RestApiService } from '../rest-api.service' ;
import { DataService } from '../data.service';

@Component({
  selector: 'app-category',
  templateUrl: './category.component.html',
  styleUrls: ['./category.component.scss']
})
export class CategoryComponent implements OnInit {
  categoryId: any;
  category: any;
  page = 1;

  constructor(
    private data: DataService,
    private activatedRoute: ActivatedRoute,
    private rest: RestApiService
  ) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe(res => {
      this.categoryId = res['_id'];
      this.getProducts();
    });
  }

  get lower() {
    return 10 * (this.page - 1) + 1;
  }

  get upper() {
    return Math.min(10 * this.page, this.category.totalProducts);
  }

  async getProducts(event ?: any) {
    if (event) {
      this.category = null;
    }
    try {
      const data = await this.rest.get(
        'http://localhost:397/api/categories/$this.categoryId?page=${this.page -1}'
      );
      data['success']  
        ? (this.category = data)
        :this.data.error(data['message']);
    }catch (error) {
      
    }
  }

}

我该如何解决这个问题?我希望得到积极的回应。

标签: javascriptangulartypescriptmongoose

解决方案


try catch代码末尾的块中,您似乎错误地将请求 URL 包装在普通引号''而不是反引号中``

这就是 mongoose 显示转换错误的原因,因为它无法解析$this.categoryId. 试试这个:

  const data = await this.rest.get(
    `http://localhost:397/api/categories/${this.categoryId}?page=${this.page -1}`
  );

推荐阅读