Working with legacy tables

While out of the box Sequelize will seem a bit opinionated it's trivial to both legacy and forward proof your application by defining (otherwise generated) table and field names.

Tables

  1. sequelize.define('user', {
  2. }, {
  3. tableName: 'users'
  4. });

Fields

  1. sequelize.define('modelName', {
  2. userId: {
  3. type: Sequelize.INTEGER,
  4. field: 'user_id'
  5. }
  6. });

Primary keys

Sequelize will assume your table has a id primary key property by default.

To define your own primary key:

  1. sequelize.define('collection', {
  2. uid: {
  3. type: Sequelize.INTEGER,
  4. primaryKey: true,
  5. autoIncrement: true // Automatically gets converted to SERIAL for postgres
  6. }
  7. });
  8. sequelize.define('collection', {
  9. uuid: {
  10. type: Sequelize.UUID,
  11. primaryKey: true
  12. }
  13. });

And if your model has no primary key at all you can use Model.removeAttribute('id');

Foreign keys

  1. // 1:1
  2. Organization.belongsTo(User, {foreignKey: 'owner_id'});
  3. User.hasOne(Organization, {foreignKey: 'owner_id'});
  4. // 1:M
  5. Project.hasMany(Task, {foreignKey: 'tasks_pk'});
  6. Task.belongsTo(Project, {foreignKey: 'tasks_pk'});
  7. // N:M
  8. User.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'});
  9. Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});