Sequelize model association won't create a new column

Solution 1:

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) {
    // Sequelize version <= 5.x
    var model = sequelize['import'](path.join(models, file))
    // Sequelize version >= 6.x
    // var model = require(path.join(models, file))(
    //   sequelize,
    //   Sequelize.DataTypes
    // );
    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'
      }]
     }
})

Solution 2:

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!