Create your first model and migration

    Learn how to create your first database model using Sequelize ORM and a migration

    Bahadir Balban

    Started Tech Buzz

    @learningexpressjs

    Your first migration

    Filename: 201901041917-CreateLeadTable.js

    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('Leads', {
          id: {
            allowNull: false,
            primaryKey: true,
            type: Sequelize.UUID,
            defaultValue: Sequelize.UUIDV4,
          },
          createdAt: {
            allowNull: false,
            type: Sequelize.DATE
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE
          },
          email: {
          	allowNull: false,
          	type: Sequelize.STRING
          },
        })
      },
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('Leads');
      }
    };

    Your first model

    Filename: Lead.js

    /* jshint indent: 2 */
    'use strict';
    module.exports = (sequelize, DataTypes) => {
      var Lead = sequelize.define('Lead', {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          
          allowNull: false,
          primaryKey: true
        },
        email: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      });
      return Lead;
    };


    Did you like this episode?

    Buzz it and share it with your friends

    Buzz2

    You Might Also Like...


    Join The Discussion

    Mike Gran

    @mike38588

    Sep 20

    what is the purpose of this code: return models.sequelize.sync().then(result =>{})? I altered my model and when i initialize the web app this code calls a create table statement defined with columns I removed from my model. I can't figure out how to remove the old columns. Does that make sense?

    Manjonka Diokou

    @manjonka

    Apr 23

    I've created my first model but only get the following error whenever I try to save an email address (Error: SequelizeValidationError: notNull Violation: Lead.id cannot be null). I've judiciously followed your tutorial, so I'm not sure what's the problem. Thanks for any suggestion.