简体   繁体   English

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

[英]Unhandled rejection SequelizeDatabaseError: relation "users" does not exist

I am getting started with Sequelize.我正在开始使用 Sequelize。 I am following the documentation they are providing on their website : http://docs.sequelizejs.com/manual/installation/getting-started.html我正在关注他们在其网站上提供的文档: 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'
    });
  });

Up until here, everything works perfectly.到这里为止,一切正常。 And the table "user" is correctly built and populated.并且“用户”表已正确构建和填充。 (Although I do not understand Sequelize appends an "s" automatically to "user", any explanation.) (虽然我不明白 Sequelize 会自动将“s”附加到“user”,任何解释。)

在此处输入图片说明

在此处输入图片说明

However when I add the following portion of code:但是,当我添加以下代码部分时:

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

I get this error :我收到此错误:

Unhandled rejection SequelizeDatabaseError: relation "users" does not exist未处理的拒绝 SequelizeDatabaseError:关系“用户”不存在

So my questions are:所以我的问题是:

  1. Why does Sequelize add an "s" to user.为什么 Sequelize 向用户添加“s”。 (I know it makes sense but shouldn't the developer decide that) (我知道这是有道理的,但开发人员不应该决定)
  2. What is causing that error?是什么导致了这个错误? I followed the documentation but it still didn't work?我遵循了文档,但它仍然不起作用?

When you are defining your model you can add configurations, in this case the option that you must add is freezeTableName prevents the names from being plural.当您定义模型时,您可以添加配置,在这种情况下,您必须添加的选项是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,
  });

There is another interesting way you can avoid this.还有另一种有趣的方法可以避免这种情况。 But you need to really focus on this way of implementation.但是您需要真正关注这种实现方式。

const User = sequelize.define("user", {
    firstname: {
      type: Sequelize.STRING
    },
    lastname: {
      type: Sequelize.STRING
    }
  });

you intentionally put user here and use users in other places of coding(Assume sequelize will automatically transform all passed model names (first parameter of define) into plural) .您故意将user放在这里并在其他编码位置使用users (假设 sequelize 会自动将所有传递的模型名称(定义的第一个参数)转换为复数)。 This way of coding will simplify your code.这种编码方式将简化您的代码。

Run that code twice.运行该代码两次。

Before running the second time, comment out the following code,在第二次运行之前,注释掉以下代码,

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

Maybe answer is not entirely connected with you question but I want to describe my experience with this error也许答案与您的问题并不完全相关,但我想描述一下我对这个错误的体验

Error: relation "users" does not exist.错误:关系“用户”不存在。

It appears Sequelize make migrations based on migrations file names and it alphabetical order.看来 Sequelize 会根据迁移文件名及其字母顺序进行迁移。 My problem was my files naming was not sorted in order to create proper connections.我的问题是我的文件命名没有排序以创建正确的连接。 If you face with this problem make sure yours migration files are fired in proper (in alphabetically) order.如果您遇到此问题,请确保您的迁移文件以正确的(按字母顺序)顺序触发。

The proper order is to first migrate table without connections (eg. table_A) and then tables with connections to table_A.正确的顺序是首先迁移没有连接的表(例如 table_A),然后是连接到 table_A 的表。

As I said this may not be answer for your particular order but I want to share my experiences because I didn't find this information on the internet when I was looking for this error.正如我所说,这可能不是您特定订单的答案,但我想分享我的经验,因为我在寻找此错误时没有在互联网上找到此信息。

The problem, in my case, was that the table users was not created.就我而言,问题是没有创建表users You can create the table manually with CREATE TABLE IF NOT EXISTS (SQL) or add the tableName = "users" in the options object:您可以使用CREATE TABLE IF NOT EXISTS (SQL) 手动CREATE TABLE IF NOT EXISTS或在选项对象中添加tableName = "users"

export const User = db.define('user',
    {
        id: {
            type: DataTypes.UUIDV4,
            autoIncrement: true,
            primaryKey: true,
        },
        name: {
            type: new DataTypes.STRING(128),
            allowNull: false,
        },
        email: {
            type: new DataTypes.STRING(128),
            allowNull: true,
        },
        password: {
            type: new DataTypes.STRING(128),
            allowNull: true,
        },
    },
    {
        freezeTableName: true,
        tableName: "users"
    }
);

This problem occurs because creating a table is an asynchronous function.出现此问题是因为创建表是一个异步函数。 The problem is, the findAll() function can get executed while the table has not been created.问题是,可以在尚未创建表的情况下执行 findAll() 函数。 to solve this, you can use:要解决此问题,您可以使用:


(async ()=>{
    await User.sync({force: true});
    // Table created
    await User.create({
      firstName: 'John',
      lastName: 'Hancock'
    });
    const users=await User.findAll();
    console.log(users);

})();



Simply append tableName: "Users" to your model configuration.只需将tableName: "Users"附加到您的模型配置中。

The easiest way I found to solve, is to explicitly set the tableName on the model.我发现解决的最简单方法是在模型上显式设置tableName As others have mentioned, sequelize defaults to the plural form of a model as the table name.正如其他人所提到的,sequelize 默认使用模型的复数形式作为表名。 For instance User, becomes Users.例如用户,成为用户。

When you query, sequelize looks after a table with the same name as your model User .查询时,sequelize 会处理与模型User同名的表。 By defining the tableName in the model, sequelize should search the correct table.通过在模型中定义tableName ,sequelize 应该搜索正确的表。 Append tableName: "Users" to your model configuration ie:tableName: "Users"到您的模型配置中,即:

 User.init(
        {
            email: DataTypes.STRING,
            password: DataTypes.STRING,
            role: DataTypes.INTEGER,
        },
        {
            sequelize,
            modelName: 'User',
            tableName: 'Users',
        }
    );

If you want Sequelize to use a singular word ('info') for a model and that same singular word for the table ('info'), you can name the model 'info' and also add tablename: 'info' to the definition of your model.如果您希望 Sequelize 为模型使用单数词 ('info') 并为表使用相同的单数词 ('info'),您可以将模型命名为 'info' 并在定义中添加tablename: 'info'你的模型。

This is a way to control Sequelize's default behavior of pluralizing model names, or not, on a table-by-table basis.这是一种在逐表的基础上控制 Sequelize 是否将模型名称复数化的默认行为的方法。

info.js
module.exports = (sequelize, DataTypes) => {
  const info = sequelize.define('info', {
    firstname: DataTypes.STRING,
    email: DataTypes.STRING,
    phone: DataTypes.STRING,
  }, {
      tableName: 'info'
  });
  return info;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM