Sequelize Model Association Won't Create a New Column

Sequelize model association won't create a new column

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!

Sequelize associations with multiple model files

First, you don't need to call sequelize.model to get a model that registered in Sequelize, you can just export a return value from sequelize.define:

const Product = sequelize.define(
"Product",
...
module.exports = Product;

Second, it seems you didn't call associate methods of all registered models.
Look at my answer here to get an idea of how to do it.

Update: to use models if you defined them like in my answer you need to access them like this:

const { sequelize } = require("../db");

const user = await sequelize.models.User.findByPk(id);
...

Sequelize model.create is not a function

You export a function that registers the User model and not the model itself. So you just need to call it passing sequelize instance and DataTypes somewhere like database.js where you will register all models and their associations or directly in models/index.js:

const UserModelConstructor = require("../models/users")
const { DataTypes } = require("sequelize");
...
const UserModel = UserModelConstructor(sequelize, DataTypes);

module.exports = {
sequelize,
User: UserModel
}

You can look at how to register multiple models and association in my other answer here

Please don't forget to remove this line

const sequelize = require("./index")

from models/users.js

Sequelize.js - model association during create or build call

The current master has support for hooks.

var User = sequelize.define('User', {
username: DataTypes.STRING
}, {
hooks: {
beforeCreate: function(user, next) {
makeYourCheck(function() {
next("a string means that an error happened.")
})
}
}
})

You can check the PR for further information: https://github.com/sequelize/sequelize/pull/894



Related Topics



Leave a reply



Submit