javascript - 为什么它显示错误: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) {
}
}
}
我该如何解决这个问题?我希望得到积极的回应。
解决方案
在try catch
代码末尾的块中,您似乎错误地将请求 URL 包装在普通引号''
而不是反引号中``
。
这就是 mongoose 显示转换错误的原因,因为它无法解析$this.categoryId
. 试试这个:
const data = await this.rest.get(
`http://localhost:397/api/categories/${this.categoryId}?page=${this.page -1}`
);
推荐阅读
- python - 如何在没有索引或切片的情况下访问 python 元组元素(其中存储了 YAML)
- android - 无法在底部导航视图中显示徽章
- c# - 如何向用户显示在前端数据库中保存为“是”的复选框?
- kotlin - android/kotlin-使用compositeDisposal(RXjava2)进行改造,单击后退按钮时不会进入响应/可抛出块
- angular - 即使模型没有发生变化,Angular ngStyle 也会无休止地运行
- postgresql - 元数据库自定义列从文本转换为整数
- javascript - 根据键的存在更新对象 else 形成一个新对象:Javascript
- javascript - 如何自动创建本地href链接?
- javascript - Chrome 浏览器未在 puppeteeer 上打开
- javascript - 动态下载数据并设置为 DevExtreme TextBox