问题描述
我似乎无法解决此问题.按下此URL http://localhost:5000/sysaccess/test 时,我收到此错误消息.
I can’t seem to get this issue resolved. I’m getting this error message when hit this URL http://localhost:5000/sysaccess/test.
(节点:34256)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):CastError:对于路径"_id",模型"sysaccess"的值"test",转换为ObjectId失败(节点:34256)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝.将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程.
(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.
在我的sysaccess.js路由中,我有以下内容:
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');
});
我已经比较了sysaccess.js路由和我的vendor.js路由,一切似乎都正常.我在vendor.js中有十几条路线,没有任何问题.我花了很多时间在google上,但是什么也没找到.有人可以告诉我我在这里想念的东西吗?预先谢谢你!
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!
推荐答案
sysaccess.js
路由器中的中间件顺序错误.
The order of middlewares in your sysaccess.js
router is wrong.
例如:
// "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) => {
// ...
});
解决方案1:使那些更具体的中间件排在那些更通用的中间件之前.
Solution 1: make those more specific middlewares come before those more general ones.
例如:
router.get('/test', (req, res) => {
// ...
});
router.get('/:id', (req, res) => {
// ...
});
解决方案2:使用next
将请求传递给下一个中间件
Solution 2: use next
to pass the request to the next middleware
例如:
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) => {
// ...
});
这篇关于CastError:对于值"route-name"的转换为ObjectId失败在路径"_id"处用于模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!