Manwal
Manwal

Reputation: 23816

Change default column name sequelize

I am working with Nodejs, Sequelize. This is following structure of my user model:

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('user', { 
    first_name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    last_name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (email, done) {
            User.find({ where: { email: email }})
                .done(function (err, user) {
                    if (err) {
                        done(err);
                    }
                    if (user) {
                        done(new Error('Email already registered'));
                    }
                    done();
                });
        }
    }
    },
    profile_image_path: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    active_flag: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: true
    },
    delete_flag: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.account),
        User.hasMany(models.user_has_contact)
      }
    }
  });
  return User;
};

By default 3 columns are created:

I don't want createdAt & updatedAt in this format, what i want is created_at and updated_at. How to change these default column name???

I have another table user_has_contact with following relationship:

{
    classMethods: {
      associate: function(models) {
        UserHasContact.belongsTo(models.user)
      }
    }
  }

Its creating userId field automatically but again i want it as user_id. Any suggestion would be appreciated!

Upvotes: 6

Views: 14503

Answers (3)

Rio Chandra
Rio Chandra

Reputation: 13

     var config=  {
     "define": {
          "underscored": true
        }
    }
var Sequelize = require("sequelize");
var sequelize = new Sequelize(database, username, password, config);

this code by ashwini jindal work for me

Upvotes: 0

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28788

sequelize.define('user', ..., {
  createdAt: 'created_at',
  updatedAt: 'updated_at',
});

http://docs.sequelizejs.com/manual/tutorial/models-definition.html#configuration

UserHasContact.belongsTo(models.user, { foreignKey: 'user_id' })

http://docs.sequelizejs.com/en/latest/docs/associations/#foreign-keys

Upvotes: 14

Ashwini Jindal
Ashwini Jindal

Reputation: 831

you can do it globally by adding this setting in your configuration as below

 var config=  {
     "define": {
          "underscored": true
        }
    }

  var Sequelize = require("sequelize");
  var sequelize = new Sequelize(database, username, password, config);

Upvotes: 20

Related Questions