sequelize.sync()执行成功但PG Admin4未创建Food表的解决方法
问题排查与解决
核心问题:未加载模型文件
你的Index.ts中没有导入Food模型,Sequelize仅会同步已注册到sequelize实例的模型。必须确保模型被加载,才能让sync()识别并创建对应数据表。
修改Index.ts,添加模型导入:
import express, { Request, Response } from "express"; import sequelize from "./src/configs/database"; // 根据你的项目结构,导入Food模型文件 import "./src/models/Food"; const app = express(); const port = 3000; sequelize .authenticate() .then(() => console.log("Connected")) .catch((error) => console.log(error)); sequelize .sync({ force: true }) .then(() => console.log("Create Model")) .catch((error) => console.log(error)); app.get("/", (req: Request, res: Response) => { res.send("Hello World!"); }); app.listen(port, () => { console.log(`Server is listening at http://localhost:${port}`); });
次要问题修正
- PostgreSQL不支持
DataTypes.NUMBER:根据价格的实际数值类型替换:- 整数价格用
DataTypes.INTEGER - 带小数的价格用
DataTypes.DECIMAL(10,2)
- 整数价格用
修改Food.ts的price字段:
price: { type: DataTypes.DECIMAL(10,2), // 按需替换为INTEGER allowNull: false, },
- UUID类型定义优化:
DataTypes.UUIDV4是生成器,字段类型应使用DataTypes.UUID:
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, unique: true, },
验证步骤
- 重启Express服务
- 在PG Admin4中刷新
seblak_super数据库的表列表(注意Sequelize默认会将模型名转为复数小写,表名应为foods) - 确认PG Admin4连接的是
localhost:5432下的seblak_super数据库,用户名密码与配置一致
内容的提问来源于stack exchange,提问作者Uletin
相关产品推荐
相关产品推荐

