You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从MySQL获取城市数据时遇Unknown column 'unique'错误及数据为空问题

问题排查与修复

问题1:终端报错 Unknown column 'unique' in 'field list'

原因

City模型定义错误,将字段约束unique和allowNull放在了name字段的外部,被Sequelize识别为单独的数据库列,但迁移文件中并未创建这两个列,因此查询时触发报错。

修复后的City模型代码

'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class City extends Model {
    static associate(models) {
      // define association here
    }
  }
  City.init({
    name: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false,
    }
  }, {
    sequelize,
    modelName: 'City',
  });
  return City;
};

问题2:Postman返回data为空对象

原因

路由层的get方法中调用cityService.getCity时未添加await关键字,cityService.getCity是异步函数,直接调用会返回Promise对象而非实际查询结果,JSON序列化Promise对象会得到空对象{}。

修复后的路由层代码

router.get('/city/:id',CityController.get);

const get = async(req,res)=>{
    try{
        // 添加await等待异步函数执行完成
        const response = await cityService.getCity(req.params.id);
    
        return res.status(StatusCodes.OK).json({
            data:response,
            success:true,
            message:"Successfully Fetched a city",
            error:{},
        });
    }catch(error){
        console.log(error);

        return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
            data:{},
            success:false,
            message:"Not able to get the city",
            error:error,
        });
    }
}

额外验证建议

  • 修复模型后重启Node.js服务,确保模型定义生效
  • 确认数据库中Cities表的name字段带有unique和not null约束
  • 测试时传入数据库中存在的id值,验证返回结果

内容的提问来源于stack exchange,提问作者rahemanali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:10:04