Search code examples
postgresqlsequelize.jssequelize-cli

Sequelize throwing: "relation "users" does not exist"


I have a User model that has a hasMany association with my Item model:

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    underscored: true,
  });
  User.associate = function(models) {
    // associations can be defined here
    User.hasMany(models.Item, {
      onDelete: 'CASCADE'
    })
  };
  return User;
};

And I have an Item model that belongs to User:

module.exports = (sequelize, DataTypes) => {
  const Item = sequelize.define('Item', {
    title: DataTypes.STRING,
    link: DataTypes.STRING,
    user_id: DataTypes.INTEGER
  }, {
    underscored: true,
  });
  Item.associate = function (models) {
    // associations can be defined here
    Item.belongsTo(models.User)
  };
  return Item;
};

When I execute User.findAll()

I get the error relation "users" does not exist.

Here is the raw SQL that is executed:

SELECT 
  "User"."id", "User"."first_name", "User"."last_name", "User"."email", 
  "User"."created_at" AS "createdAt", "User"."updated_at" AS "updatedAt", 
  "Items"."id" AS "Items.id", "Items"."title" AS "Items.title", 
  "Items"."link" AS "Items.link", "Items"."user_id" AS "Items.user_id", 
  "Items"."created_at" AS "Items.createdAt", "Items"."updated_at" AS "Items.updatedAt", 
  "Items"."user_id" AS "Items.UserId" 
FROM "users" AS "User" 
LEFT OUTER JOIN "items" AS "Items" ON "User"."id" = "Items"."user_id";

Items attributes are prepended by "Items" which is correct but Users is prepended by "User" which is not correct. Also not sure why it says FROM "users" AS "User" instead of FROM "Users"

In my config I used underscored: true and I'm using a postgres database. There is a "Users" table and an "Items" table in my postgres database.

"pg": "^7.12.1",
"sequelize": "^5.18.4"
"sequelize-cli": "^5.5.1"

Solution

  • Switch the config/config.js from:

    require('dotenv').config()
    
    module.exports = {
      development: {
        url: process.env.DEV_DATABASE_URL,
        dialect: 'postgres'
      }
    }
    

    to:

    require('dotenv').config()
    
    module.exports = {
      development: {
        url: process.env.DEV_DATABASE_URL,
        database: 'database_development',
        dialect: 'postgres'
      }
    }
    

    Sequelize requires a database key in the config!

    https://github.com/sequelize/cli/blob/77a9a76420e36cfbcb82fe3c9c6a12d52c768104/src/commands/database.js#L88