Node.js 当id在单独的文件中定义时,req.params.id返回未定义

Node.js 当id在单独的文件中定义时,req.params.id返回未定义,node.js,express,mongoose,Node.js,Express,Mongoose,当我将req.params.id与mongoose一起使用时,它返回未定义。我相当确定这是因为我在我的app.js中定义了id参数,而不是我的路由文件 路由文件: //NEW - Form for adding new course router.get("/new", function(req, res) { // find course by id Course.findById(req.params.id).exec(function(err, foundCourse) {

当我将
req.params.id
与mongoose一起使用时,它返回未定义。我相当确定这是因为我在我的
app.js
中定义了id参数,而不是我的路由文件

路由文件:

//NEW - Form for adding new course
router.get("/new", function(req, res) {
    // find course by id
    Course.findById(req.params.id).exec(function(err, foundCourse) {
        if(err) {
            res.redirect("back");
        } else {
            //show template with correct id
            res.render("lectures/new", {course: foundCourse});
        }
    });
});
app.use("/courses/:id/lectures", lectureRoutes);
App.js文件:

//NEW - Form for adding new course
router.get("/new", function(req, res) {
    // find course by id
    Course.findById(req.params.id).exec(function(err, foundCourse) {
        if(err) {
            res.redirect("back");
        } else {
            //show template with correct id
            res.render("lectures/new", {course: foundCourse});
        }
    });
});
app.use("/courses/:id/lectures", lectureRoutes);
是否有任何方法可以修复此问题,以便我可以从路由文件访问id参数

编辑: 我在浏览器中使用的路径:

http://localhost:7000/courses/5a4111286ae1111f541c3d88/lectures/new

为此,必须启用名为
mergeParams
的选项

const router = express.Router({ mergeParams: true });

请参阅文档。

要使其正常工作,您必须启用名为
mergeParams
的选项

const router = express.Router({ mergeParams: true });

请参阅文档。

您可以发布您在浏览器或测试中使用的
路径来调用它吗?现在添加了路径我不确定,但我认为
findById
不会将id强制转换为
ObjectId
,这是查询中需要的。另外,您是否记录了req.params.id的值?如果我删除app.use路径,而是将其直接插入到路由文件中,这将完全正常。当我记录req.params.id时,我没有定义。您可以发布您在浏览器中使用的
路径
或测试来调用它吗?现在添加了路径我不确定,但我认为
findById
不会将id强制转换为查询中需要的
ObjectId
。另外,您是否记录了req.params.id的值?如果我删除app.use路径,而是将其直接插入到路由文件中,这将完全正常。当我记录req.params.id时,我没有定义。