问题描述
在这里输入代码const express=require('express');const 路由器 = express.Router();const asyncHandler = require('express-async-handler');const Product=require('../models/productModel');router.get('/', asyncHandler(async (req,res)=>{const products=await Product.find({})res.send(产品)}));router.get('/:id',asyncHandler(async(req,res)=>{const product=await Product.findById(req.params.id)如果(产品){res.json(产品)}别的{res.status(404).json({消息:未找到产品"})}`在此处输入代码`}));在这里输入代码module.exports=router`在此处输入代码`在这里,我在邮递员或浏览器中获取产品和带有 ID 的产品数据,但如果我输入错误的 ID,它会显示 castError 并且在控制台日志中它会显示它是内部服务器 500 错误
我将尝试更广泛地解释错误,以防其他人碰巧明白原因.
_id
进入 Mongo 是以特定方式创建的.您可以查看 docs,其中解释了 _id
是一个名为 ObjectId
的对象,它由以下内容组成:
- 一个 4 字节的时间戳值,代表 ObjectId 的创建,以 Unix 纪元以来的秒数为单位
- 一个 5 字节的随机值
- 一个 3 字节递增计数器,初始化为随机值
这意味着不会接受任何值.
当您执行与 _id
匹配的查询时,mongo 需要一个 ObjectId
(或者至少是可以解析为 string
的类型)).
因此,如果您尝试使用错误的 _id
,(例如 -1
或 XXX
),则会抛出错误.Mongo 无法将 -1
解析为 ObjectId
如果您正在测试您的应用程序并且想要使用伪造的 _id
,您需要生成一个有效的 _id
.
使用 mongoose
你可以调用使用这个函数:mongoose.Types.ObjectId()
.
返回的值是新生成的_id
,所以格式有效.
enter code here
const express=require('express');
const router= express.Router();
const asyncHandler = require('express-async-handler');
const Product=require('../models/productModel');
router.get('/', asyncHandler(async (req,res)=>{
const products=await Product.find({})
res.send(products)
}));
router.get('/:id',asyncHandler(async(req,res)=>{
const product=await Product.findById(req.params.id)
if(product){
res.json(product)
}else{
res.status(404).json({message:"product not found"})
}`enter code here`
}));
enter code here
module.exports=router`enter code here`
here i get data of products and product with id in postman or browser but if i enter wrong id it shows castError and in console log it shows it is internal server 500 error
I will try to explain the error more extensively in case someone else happens to understand why.
_id
's into Mongo are created in a specific way. You can check the docs where is explained the _id
is an object called ObjectId
and is compound by:
- A 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch
- A 5-byte random value
- A 3-byte incrementing counter, initialized to a random value
That implies that not just any value will be accepted.
When you do a query matching the _id
, mongo expect an ObjectId
(or at least, come type that could be parsed as string
).
So if you try to use a bad _id
, (for example -1
or XXX
), the error will be thrown. Mongo can't parse -1
to ObjectId
If you are testing your application and you want to use a fake _id
you need to generate a valid one.
Using mongoose
you can call use this function: mongoose.Types.ObjectId()
.
The value return is a new _id
generated, so it has a valid format.
这篇关于CastError: Cast to ObjectId 因值“XXX"而失败;在路径“_id"处对于模型“产品"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!