我正在尝试使用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);
});
当我获得对上述路线的请求时,我得到了该错误:
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
}
});
我该如何解决这个问题?
答案 0 :(得分:0)
[-1]
和product/:_id
在路由上下文中是“相同的” ...因此,即使您发送product/:category
请求,服务器也会计算出匹配的第一个端点。
解决方案1::使每条路线唯一。
product/:category
解决方案2:使用// _id
app.get('product/_id/:_id', async (req, res)=>{
const productById = await product.find({_id: req.params._id});
res.json(productById);
});
// category
app.get('product/category/:category', async (req, res)=>{
const productByCategory = await product.find({category: req.params.category});
res.json(productByCategory);
});
...
request.body
注意:请注意NoSQL注入。
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20Injection