【发布时间】:2020-05-11 10:27:37
【问题描述】:
我正在尝试使用 mongodb 和 nodejs 制作应用程序。我制作了一条具有:id 参数的特殊路线,并且运行良好。
我已经创建了另一个包含product/:category 的获取路线。当我每次收到该错误时向该路由发送请求时:
CastError: Cast to ObjectId failed for value "(here is my req.params.category)" at path "_id" for model "Product"
我的路线是:
// product is my model I called it in top of the file
app.get('product/:category', async (req, res)=>{
const productByCategory = await product.find({category: req.params.category});
res.json(productByCategory);
});
当我向上面的路线发出 get 请求时,我得到了那个错误:
CastError: Cast to ObjectId failed for value "(here is my req.params.category)" at path "_id" for model "Product"
我的产品型号是:
const ProductSchema = new mongoose.Schema({
title:{
type: String,
required: true
},
description:{
type: String,
min: 40,
required: true
},
category:{
type: String,
required: true
},
price:{
type: Number,
required: true
},
imageUrl:{
type: String,
required: true
},
quantity:{
type: Number,
required: true
},
comments: [{
type: Object
}],
seller: {
sellerId:{
type: String,
required: true
},
username:{
type: String,
required: true
},
shopName:{
type: String,
required: true
},
category:{
type: String,
required: true
}
},
location: {
type: "String",
required: true
},
date:{
type: Date,
default: Date.now
}
});
我该如何解决这个问题?
【问题讨论】:
-
你对
:_id的溃败是这样的:app.get('product/:_id'? -
@Valijon 不,我想为类别路由。
-
请发布所有路线
-
@Valijon 你的代码对我有用。无需发布所有路线。
标签: javascript node.js mongodb mongoose