我刚开始使用 Sequelize,但有点陷入困境。我尝试连接我的控制器、路线、模型和其他内容,但在尝试访问我的路线(localhost:3000 / api / carousel)时收到此错误:
TypeError: Cannot read properties of undefined (reading 'findAll')
at getAllCarouselItems (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\controllers\carousel-item_controller.js:6:47)
at Layer.handle [as handle_request] (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\index.js:280:10)
at Function.handle (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\index.js:175:3)
at router (C:\Users\theob\OneDrive\Documents\DEV\le_burguignon\back\node_modules\express\lib\router\index.js:47:12)
这是我的控制器,其中 findAll 方法不起作用:
const CarouselItem = require('../models/carousel-item');
const db = require('../config/sequelize');
async function getAllCarouselItems(req, res) {
try {
const carouselItems = await db.CarouselItem.findAll();
res.json(carouselItems);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server Error' });
}
}
module.exports = { getAllCarouselItems };
有什么我遗漏的吗?
我尝试使用控制台日志,使用这些错误在线搜索,甚至向聊天 gpt 寻求帮助,但作为这项技术的初学者,我感到困惑,不知道在哪里查看。
您遇到的错误表明正在对未定义的值调用 findAll 方法。查看您的代码,您似乎正在使用 db.CarouselItem.findAll()。 CarouselItem 可能未按预期导出到 db 对象中。 尝试将其添加到 models/carousel-item.js :
// This line is crucial for exporting the model
module.exports = CarouselItem;
当我仍在尝试时,我可能已经弄清楚了,但你能告诉我这是否真的是原因,以便我能理解吗?
所以我想我应该添加一个sequelize.authenticate来测试我与数据库的连接,然后一切就开始工作了。我是否误解了它的目的,那么整个事情是否需要它才能真正发挥作用?