0
votes

Why is it that in some of my models, sequelize WON’T create a new column for foreignkey? BUT it does create for other models??? It’s frustrating and weird. For instance, in this User model, sequelize won’t create role_id.

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: { type: DataTypes.BIGINT, allowNull: false, autoIncrement: true, unique: true, primaryKey: true },
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    User.belongsTo(models.Role, { foreignKey: 'role_id' });
  };
  return User;
};

This is a similar question: Sequelize not creating model association columns BUT! It wasn't answered.

I've spent hours on this, I did everything like:

  1. Reading this thoroughly: https://sequelize.org/master/manual/assocs.html
  2. Experimenting, like creating a new dummy model, with name NewUser. It works! But again not with User name.
  3. Posted on Sequelize's Slack channel.

After this Stackoverflow question, I will seek help from their Github's issue page.

I'm thinking I can just define the column role_id instead of adding it through the associate function.

2
Can you show differences between a model that has created FK and a model without created FK? Is there a difference in a registration process of these two models? - Anatoly
Hey Antoly, literally no difference at all! Like I mentioned, I tried creating a dummy model with the same content BUT different filename, like ZUser.js (model defined as ZUser, and I can see the roldeId column being added by Sequelize. I really now don't know what's happening. I think it's because of the class name defined as User???? - Glenn Posadas
Maybe when you run 'sync' User table already exists and sequelize does not alter it while new ZUser model leads to creating a new table with all columns and FKs that are presenting in it at the moment - Anatoly
I do sync force true when I'm in development/local. Like this: db.sequelize.sync({ force : true}). I also have tried deleting ALL the tables (But haven't tried re-creating database). I also tried deleting migrations, and re-running db:migrate/ - Glenn Posadas
Wait! You either use 'sync' or migrations but not both! - Anatoly

2 Answers

2
votes

All models should be registered in one place as long as their associations:

database.js

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const db = {}
const models = path.join(__dirname, 'models') // correct it to path where your model files are

const sequelize = new Sequelize(/* your connection settings here */)

fs
  .readdirSync(models)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.Sequelize = Sequelize // for accessing static props and functions like Op.or
db.sequelize = sequelize // for accessing connection props and functions like 'query' or 'transaction'

module.exports = db

some_module.js

const db = require('../database')
...
const users = await db.user
   .findAll({
     where: {
      [db.Sequelize.Op.or]: [{
        first_name: 'Smith'
      }, {
        last_name: 'Smith'
      }]
     }
})

1
votes

Thanks to Anatoly for keeping up with my questions about Sequelize like this.

After so many trials and errors, I figured that the issue was caused by the registration of my routes like:

require("./app/routes/user/user.routes")(app)

in my app.js or server.js. These routes registration was added before the db.sync!

So what I did was, I call these routes registration after that db.sync, like so:

const db = require("./app/models")

if (process.env.NODE_ENV === "production") {
  db.sequelize.sync().then(() => {
    useRoutes()
  })
} else {
  db.sequelize.sync({ force: true }).then(() => {
    console.log("Drop and re-sync db.")
    useRoutes()
  })
}

function useRoutes() {
  console.log("Use routes...")
  require("./app/routes/user/user.routes")(app)
  require("./app/routes/auth/auth.routes")(app)
}

Voila, fixed!