gpt4 book ai didi

node.js - Actor 错误: Cast to ObjectId failed for value "route-name" at path "_id" for model

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:25 24 4
gpt4 key购买 nike

我似乎无法解决这个问题。当点击此 URL http://localhost:5000/sysaccess/test 时,我收到此错误消息。

( Node :34256)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝(拒绝ID:1):CastError:模型“sysaccess”的路径“_id”处的值“test”转换为ObjectId失败( Node :34256)[DEP0018] DeprecationWarning:未处理的 promise 拒绝已被弃用。将来,未处理的 Promise 拒绝将会以非零退出代码终止 Node.js 进程。

在我的 sysaccess.js 路由中,我有这个:

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 路由与供应商.js 路由进行了比较,一切看起来都正常。我在vendor.js中有十几条路线,没有任何问题。我花了很多时间谷歌这个但没有找到任何东西。有人可以告诉我我在这里缺少什么吗?预先感谢您!

最佳答案

您的 sysaccess.js 路由器中的中间件顺序错误。

例如:

// "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:使那些更具体的中间件位于那些更通用的中间件之前。

例如:

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

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

解决方案2:使用next将请求传递给下一个中间件

例如:

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) => {
// ...
});

关于node.js - Actor 错误: Cast to ObjectId failed for value "route-name" at path "_id" for model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com