CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

蓝咒 提交于 2019-11-29 17:20:51

The order of middlewares in your sysaccess.js router is wrong.

For example:

// "GET /sysaccess/test" will be processed by this middleware
router.get('/:id', (req, res) => {
  let id = req.params.id; // id = "test"
  Foo.findById(id).exec().then(() => {}); // This line will throw an error because "test" is not a valid "ObjectId"
});

router.get('/test', (req, res) => {
  // ...
});

Solution 1: make those more specific middlewares come before those more general ones.

For example:

router.get('/test', (req, res) => {
  // ...
});

router.get('/:id', (req, res) => {
  // ...
});

Solution 2: use next to pass the request to the next middleware

For example:

router.get('/:id', (req, res, next) => {
  let id = req.params.id;

  if (id === 'test') { // This is "GET /sysaccess/test"
    return next(); // Pass this request to the next matched middleware
  }

  // ...
});

router.get('/test', (req, res) => {
  // ...
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!