Sequelize服务搭建报错TypeError: Customer.findById不是函数求助
解决Sequelize中
Customer.findById is not a function的问题 首先,这个错误的核心原因是Sequelize版本更新后API的变化:从Sequelize v5开始,findById()方法已经被废弃并移除了,取而代之的是findByPk()(Find By Primary Key)方法,专门用于通过主键查询数据。
接下来,我们一步步修复你的代码,同时解决其他潜在的问题:
1. 替换findById为findByPk
修改controller.js中的findById方法,同时优化错误处理逻辑:
//GET BY ID exports.findById = (req, res) => { // 不需要JSON.stringify,findByPk会自动处理参数类型 Customer.findByPk(req.params.id).then(customer => { if (!customer) { return res.status(404).json({msg: "Customer not found with id " + req.params.id}); } res.json(customer); }).catch(err => { console.log(err); res.status(500).json({msg: "error", details: err}); }); };
2. 修复Update和Delete的ID获取逻辑
你的路由配置中,Update和Delete的ID是通过URL参数/:id传递的,但代码里却从req.body.id获取,这既不符合RESTful规范,也会导致请求失败。修改这两个方法:
Update方法修改:
//UPDATE A CUSTOMER exports.update=(req,res)=>{ const id=req.params.id; // 从URL参数获取id Customer.update(req.body,{where:{id:id}} ) .then(num => { if (num == 1) { res.status(200).json( { msg: "Updated Successfully -> Customer Id = " + id } ); } else { res.status(404).json({msg: `Cannot update Customer with id=${id}. Maybe Customer was not found or req.body is empty!`}); } }) .catch(err => { res.status(500).json({msg: "Error updating Customer with id=" + id, details: err}); }); }
Delete方法修改:
//DELETE A CUSTOMER BY ID exports.delete=(req,res)=>{ const id=req.params.id; // 从URL参数获取id Customer.destroy({where : {id:id} }) .then(num => { if (num == 1) { res.status(200).json( { msg: 'Deleted Successfully -> Customer Id = ' + id } ); } else { res.status(404).json({msg: `Cannot delete Customer with id=${id}. Maybe Customer was not found!`}); } }) .catch(err => { res.status(500).json({msg: "Could not delete Customer with id=" + id, details: err}); }); }
3. 额外优化说明
- 增加了
num == 1的判断,用来验证是否真的有数据被更新/删除,返回更精准的状态码和提示信息 - 移除了
JSON.stringify(req.params.id)的冗余操作,findByPk可以直接接收字符串类型的主键,内部会自动转换匹配
验证步骤
- 保存修改后的代码
- 重启服务器(执行
npm start) - 用Postman重新测试GET
/api/customers/:id、PUT/api/customers/:id、DELETE/api/customers/:id接口,所有基于ID的操作应该可以正常工作了
内容的提问来源于stack exchange,提问作者Yasik raam
相关产品推荐
相关产品推荐

