Search code examples
databasesequelize.jsmigrate

node.js sequelize no primary keys when migrating


This is my create_user_table migration in my node.js project.

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("comments", {
      content: {
        type: Sequelize.STRING(20),
        allowNull: false
      },
      lastName: {
        type: Sequelize.STRING(20),
        allowNull: false
      }
    })
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("comments")
  }
};

After running sequelize db:migrate this is the result:

sequelize db:migrate

Sequelize CLI [Node: 10.15.2, CLI: 5.4.0, ORM: 5.8.5]

Loaded configuration file "config/config.json".
Using environment "development".
== 20190507193540-create_comment_table: migrating =======
== 20190507193540-create_comment_table: migrated (0.021s)

== 20190507195058-create_user_table: migrating =======
== 20190507195058-create_user_table: migrated (0.011s)

When I run describe users; in mysql CLI, the table does not include an ID?

   +----------+-------------+------+-----+---------+-------+
    | Field    | Type        | Null | Key | Default | Extra |
    +----------+-------------+------+-----+---------+-------+
    | username | varchar(20) | NO   |     | NULL    |       |
    | lastName | varchar(20) | NO   |     | NULL    |       |
    +----------+-------------+------+-----+---------+-------+

And to completely make sure, I've also tried.

mysql> show index from users where id = 'PRIMARY';
ERROR 1054 (42S22): Unknown column 'id' in 'where clause'

Solution

  • You must manually declare an id field in your model and migration file, e.g.:

    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable("comments", {
          id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
          },
          content: {
            type: Sequelize.STRING(20),
            allowNull: false
          },
          lastName: {
            type: Sequelize.STRING(20),
            allowNull: false
          }
        })
      },
    
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable("comments")
      }
    };