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

Sequelize无法插入新行,查询仅返回ID问题求助

问题描述

我编写了创建用户的后端函数,console.log能正常输出传入的用户数据,但执行时触发数据库非空约束错误,且使用findAll查询时仅能获取id字段,无法拿到username、email或password字段。

创建用户函数

async create(data) {
    try {
      console.log("User ", data);
      const newUser = await models.User.create({
        ...data,
        password: await bcrypt.hash(`${data.password}`, 10),
      });
      delete newUser.dataValues.password;
      return newUser;

    } catch(error) {
      console.error("Error creating user:", error);
      throw new Error('Signup failed'); // or handle the error accordingly
    }
  }

传入的data数据

{ 
username: 'test', email: 'sometest@gmail.com', password: 'Hello1234#'
}

错误信息

Executing (default): INSERT INTO "user" ("id") VALUES (DEFAULT) RETURNING "id";
name: 'SequelizeDatabaseError',
parent: error: null value in column "username" of relation "user" violates not-null constraint
{
length: 236,
severity: 'ERROR',
code: '23502',
detail: 'La fila que falla contiene (6, null, null, null).',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'user',
column: 'username',
dataType: undefined,
constraint: undefined,
file: 'execmain.c',
line: '1974',
routine: 'ExecConstraints',
sql: 'INSERT INTO "user" ("id") VALUES (DEFAULT) RETURNING "id";',
parameters: []
}

相关代码与配置

User模型定义

const { Model, DataTypes } = require("sequelize");
const USER_TABLE = "user";
const UserTableSchema = {id: {type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true,allowNull: false},username: {type: DataTypes.STRING,allowNull: false,},email: {type: DataTypes.STRING,allowNull: false,},password: {type: DataTypes.STRING,allowNull: false,},};
class User extends Model {// eslint-disable-next-line no-unused-varsstatic associate(_models) {// No associations to define}
static config(sequelize) {return {sequelize,tableName: USER_TABLE,modelName: "User",timestamps: false,};}}
module.exports = { USER_TABLE, UserTableSchema, User };

Sequelize配置文件

const { Sequelize } = require('sequelize');
const { config } = require('../../../config/config');
const setupModels = require('./models');

// Build the database connection URI
const USER = encodeURIComponent(config.dbUser);
const PASSWORD = encodeURIComponent(config.dbPassword);
const URI = `postgres://${USER}:${PASSWORD}@${config.dbHost}:${config.dbPort}/${config.dbName}`;

// Set the options for Sequelize
const options = {
  dialect: config.dialect,
  host: config.dbHost,
  define: {
    timestamps: false,
  },
  dialectOptions: {
    ssl: false,
  },
  logging: console.log,
};

// Create a new Sequelize instance with the connection URI and options
const sequelize = new Sequelize(URI, options);

// Setup the models using the created Sequelize instance
setupModels(sequelize);

module.exports = sequelize;

项目依赖版本

"@hapi/boom": "^10.0.0",
"axios": "^0.27.2",
"bcrypt": "^5.0.1",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"crypto-js": "^4.1.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"fs-extra": "^10.1.0",
"handlebars": "^4.7.7",
"html-entities": "^2.3.3",
"html-pdf": "^3.0.1",
"i18n": "^0.15.0",
"ionicons": "^6.0.3",
"joi": "^17.6.0",
"joi-to-swagger": "^6.2.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"multer": "^1.4.5-lts.1",
"nodemon": "^2.0.20",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pg": "^8.7.3",
"pg-hstore": "^2.3.4",
"puppeteer": "^19.2.2",
"sanitize-html": "^2.7.1",
"sequelize": "^6.21.4",
"sequelize-cli": "^6.5.1",
"sharp": "^0.30.7",
"swagger-autogen": "^2.21.5",
"swagger-ui-express": "^4.5.0"
解决方案

问题核心是User模型未正确注册字段——你定义了UserTableSchema但未调用init方法将其与Model绑定,导致Sequelize无法识别模型的字段信息,插入时只传入了自增id,查询也只能返回id。

修改User模型,添加字段初始化逻辑:

const { Model, DataTypes } = require("sequelize");
const USER_TABLE = "user";
const UserTableSchema = {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
  },
};

class User extends Model {
  // eslint-disable-next-line no-unused-vars
  static associate(_models) {
    // No associations to define
  }

  static config(sequelize) {
    return {
      sequelize,
      tableName: USER_TABLE,
      modelName: "User",
      timestamps: false,
    };
  }
}

// 关键:调用init注册字段
User.init(UserTableSchema, User.config(null));

module.exports = { USER_TABLE, UserTableSchema, User };

同时检查setupModels函数,确保它正确传入sequelize实例完成模型注册:

// setupModels.js示例
const { User, UserTableSchema } = require('./user.model');

module.exports = (sequelize) => {
  User.init(UserTableSchema, {
    sequelize,
    tableName: User.USER_TABLE,
    modelName: "User",
    timestamps: false,
  });
};

修改后,Sequelize就能识别模型的所有字段,插入时会自动包含username、email等数据,查询也能返回完整的用户信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:38:13