Node.js 猫鼬:小径上的卡斯特罗”_id";当未调用ID时

Node.js 猫鼬:小径上的卡斯特罗”_id";当未调用ID时,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,有问题的堆栈:节点、EJS、Mongo、Mongoose 我的路由设置为: app.get('/products', async (req,res) => { const products= await Product.find({}); res.render('products/index', {products}); }) app.get('/products/:id', async (req,res) =>{ const {id} = req.para

有问题的堆栈:节点、EJS、Mongo、Mongoose

我的路由设置为:

app.get('/products', async (req,res) => {
    const products= await Product.find({});
    res.render('products/index', {products});
})

app.get('/products/:id', async (req,res) =>{
    const {id} = req.params;
    const product = await Product.findById(id);
    res.render('products/show', {product});
})

app.get('/products/new', (req,res)=>{
    res.render('products/new');
})
我得到了这个错误:

CastError: Cast to ObjectId failed for value "new" at path "_id" for model "Product"
最后,我通过将/new路由移动到/:id路由之上,修复了这个错误

我的问题是:为什么要修复它?我没有在/新路线中呼叫{id}。除了res.render中的我的EJS文件外,/new路由没有调用任何东西。我在互联网上找不到任何理由来解释为什么在代码中将路由移到更高的位置可以解决这个问题。

当上面定义了路由“app.get”(“/products/:id”)”时,它会将“/products/”之后的每个值都视为id参数。例如,如果调用“/products/new”路由,app.get(“/products/:id”)路由会捕获认为id param的值为“new”的请求,并开始处理该请求,而不允许其到达预期位置


但是如果在app.get('/products/:id')之前定义'app.get('/products/new')路由,它将捕获任何针对'/products/new'路由的请求,并保留包含id参数的请求。

,现在一切都有意义了。非常感谢。很乐意帮忙!!