markvgti
markvgti

Reputation: 4619

Why doesn't sequelize-cli include the ID in the model file?

When I run the following command:

sequelize-cli model:create --name User --attributes "dispName:string,email:string,phoneNum1:string"

I end up with the following migration file:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      dispName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      phoneNum1: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

and the following model file:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    dispName: DataTypes.STRING,
    email: DataTypes.STRING,
    phoneNum1: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

Questions:

  1. Why doesn't the model file contain the definition for id?
  2. If I change the name and/or definition of the primary key field (the key will be generated externally and will be set on an object before it is saved), then do I have to include the definition of the ID field in the model file? Why/why not?

Versions:

[Node: 12.14.1, CLI: 5.5.1, ORM: 5.21.3]

The following do not answer my question:

Upvotes: 1

Views: 513

Answers (1)

Anatoly
Anatoly

Reputation: 22793

If you don't declare PK in your model sequelize assumes you have the id PK. This is by design. And yes you can rename your PK in the model. Just don't forget to setup PK in the mode properly according to a real PK in your DB.

Upvotes: 2

Related Questions