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

后端 未结 1 2134
面向向阳花
面向向阳花 2020-12-21 22:06

I can’t seem to get this issue resolved. I’m getting this error message when hit this URL http://localhost:5000/sysaccess/test.

(node:34256) UnhandledPromiseRejecti

相关标签:
1条回答
  • 2020-12-21 22:16

    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) => {
      // ...
    });
    
    0 讨论(0)
提交回复
热议问题