问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/64755520/casterror-cast-to-objectid-failed-for-value-xxx-at-path-id-for-model-prod