问题
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) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "test" at path "_id" for model "sysaccess" (node:34256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
In my sysaccess.js routes I have this:
const express = require('express');
const csv = require('csv-express');
const mongoose = require('mongoose');
const router = express.Router();
const {ensureAuthenticated} = require('../helpers/auth');
const Sysaccess = mongoose.model('sysaccess');
const Vendor = mongoose.model('vendor');
router.get('/test', (req, res) => {
res.send('ok');
});
I've compare sysaccess.js routes with my vendors.js routes and everything appears ok. I have over a dozen routes in vendor.js without any issues. I spent a good amount of time google this but haven't found anything. Can someone tell me what I'm missing here. Thank you in advance!
回答1:
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) => {
// ...
});
来源:https://stackoverflow.com/questions/49700471/casterror-cast-to-objectid-failed-for-value-route-name-at-path-id-for-mode