为何无法在Sequelize模型中创建记录?TypeError报错排查
问题原因及解决方案
核心错误原因
你在CityRepo中错误导入了模型模块,而非具体的City模型:
const City = require('../models/index');
../models/index.js默认导出的是包含所有模型的对象(结构类似{ City: CityModel }),直接调用City.create自然会提示“不是函数”——因为这个对象本身没有create方法,create是挂载在具体模型实例上的。
修复步骤
1. 修正模型导入方式
将CityRepo中的导入语句改为以下任意一种:
// 方式一:直接导入City模型文件 const City = require('../models/city'); // 方式二:从index.js导出的对象中解构出City模型 const { City } = require('../models/index');
2. 修正删除方法的错误调用
Sequelize模型没有deleteCity方法,删除记录需要使用destroy方法,修改deleteCity函数:
async deleteCity(name) { try { await City.destroy({ where: { name } // 通过name条件匹配删除目标 }); } catch(error) { console.log(error); } }
3. 处理异步调用的未捕获异常
启动代码中调用createCity是异步操作,建议添加await和错误捕获,避免未处理的Promise拒绝:
app.listen(3000, async () => { console.log(`Server started at ${PORT}`); const cityRepo = new CityRepo(); try { await cityRepo.createCity({ name: "New Delhi" }); console.log("城市创建成功"); } catch (err) { console.log("创建失败:", err); } })
完整修改后的CityRepo代码
const { City } = require('../models/index'); class CityRepo { async createCity({ name }) { try { const city = await City.create({ name }); return city; } catch(error) { console.log(error); throw error; // 抛出错误让上层调用方处理 } } async deleteCity(name) { try { await City.destroy({ where: { name } }); } catch(error) { console.log(error); throw error; } } } module.exports = CityRepo;
内容的提问来源于stack exchange,提问作者Vatsal A Mehta
相关产品推荐
相关产品推荐

