首页 > 解决方案 > 未处理的拒绝 SequelizeDatabaseError:关系“用户”不存在

问题描述

我开始使用 Sequelize。我正在关注他们在其网站上提供的文档:http: //docs.sequelizejs.com/manual/installation/getting-started.html

const Sequelize = require('sequelize');
const sequelize = new Sequelize('haha', 'postgres', 'postgres', {
  host: 'localhost',
  dialect: 'postgres',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});


sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


  const User = sequelize.define('user', {
    firstName: {
      type: Sequelize.STRING
    },
    lastName: {
      type: Sequelize.STRING
    }
  });

  // force: true will drop the table if it already exists
  User.sync({force: true}).then(() => {
    // Table created
    return User.create({
      firstName: 'John',
      lastName: 'Hancock'
    });
  });

直到这里,一切都完美无缺。并且表“用户”已正确构建和填充。(虽然我不明白 Sequelize 会自动将“s”附加到“用户”,但有任何解释。)

在此处输入图像描述

在此处输入图像描述

但是,当我添加以下代码部分时:

User.findAll().then(users => {
  console.log(users)
})

我收到此错误:

未处理的拒绝 SequelizeDatabaseError:关系“用户”不存在

所以我的问题是:

  1. 为什么 Sequelize 向用户添加“s”。(我知道这是有道理的,但开发人员不应该决定)
  2. 是什么导致了这个错误?我遵循了文档,但它仍然没有工作?

标签: javascriptnode.jspostgresqlsequelize.jspgadmin

解决方案


在定义模型时,您可以添加配置,在这种情况下,您必须添加的选项是freezeTableName防止名称为复数。

const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
}, {
    // disable the modification of table names; By default, sequelize will automatically
    // transform all passed model names (first parameter of define) into plural.
    // if you don't want that, set the following
    freezeTableName: true,
  });

推荐阅读