Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • id
  • createdAt
  • updatedAt

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!

like image 945
Manwal Avatar asked Apr 23 '15 15:04

Manwal


1 Answers

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);
like image 105
Ashwini Jindal Avatar answered Sep 28 '22 06:09

Ashwini Jindal