Search code examples
node.jssequelize.jssequelize-cli

Customizing sequelize-cli generated IDs


Created a model using:

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

Which resulted in the following migration:

'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
      },
      // plus others...
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

I want to change the automatically defined ID to:

cognitoId: {
  allowNull: false,
  primaryKey: true,
  type: Sequelize.STRING(100)
}

So:

  1. Will sequelize be able to recognize this as the ID?
  2. Where all do I need to make this change? I could only identify the migration file.
  3. The model file doesn't have a definition for the cognitoId (or the original auto-generated id field): how will I be able to get the value of a User instance's cognitoId (in the data returned by queries)?
  4. Will changing the auto-generated id field have repercussions down the line?
  5. Is the field name id "magical"? I.e., does the primary key have to be named id?
  6. Is there a better way to do this?
  7. Will changing the types of the fields from Sequelize.STRING to Sequelize.STRING(100) create any issues down the line?
  8. Why doesn't the models file generated by sequelize-cli have the id field defined?

When generating models+migrations from the command-line I couldn't find any syntax to specify the ID or any other customization for the fields.

Using:

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

PS: relatively new to NodeJS & completely new to Sequelize.


Solution

    1. Yes
    2. You should declare custom named PK in your model
    3. see p.2. If you don't declare PK in your model then sequelize assumes you have id PK with an integer type, autoincremented. If you wish to assign your PK another name you should declare it in the model.
    4. Depends on what changes you make
    5. It is the default PK name in sequelize (see p.3). You can set different name to your PK manually declaring it in your model (see p.3)
    6. Personally I prefer to declare all PKs in my models even if they have id name and default PK type and value.
    7. No issues if all PK values do not exceed this length
    8. see p.3

    You can define names and types only for fields while generating models from the command line.