'Associations with Sequelize Node/Express.js

I got some trouble understanding how associations works with Sequelize. I am working on a project which have almost the same features that Reddit and therefore I am trying to associate the User table to the Post table as a 1:N associations.

User Model:

const { Sequelize, Model, DataTypes } = require ('sequelize');
const db = require('../config/db');
const Post = require('./Post')


class User extends Model{}

User.init({
    id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    username:{
        type: DataTypes.STRING,
        unique: true
    },
    email:{
        type: DataTypes.STRING
    },
    password:{
        type: DataTypes.STRING
    },
    isAdmin:{
        type: DataTypes.BOOLEAN,
        defaultValue: false
    }
}, {sequelize: db, modelName:'User'}
);


User.hasMany(Post,{as: 'posts', foreignKey: 'id'});

User.sync();

module.exports = User;

Post Model:

const { Sequelize, Model, DataTypes } = require ('sequelize');
const db = require('../config/db');
const User = require('./User');


class Post extends Model{}

Post.init({
    id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    text:{
        type: Sequelize.STRING
    },
    image:{
        type: Sequelize.STRING
    },
    likes:{
        type: Sequelize.INTEGER,
    }
}, {sequelize: db, modelName:'Post'}
)


Post.sync();

module.exports = Post;

When I launch my app, I can see that it mention that post have the foreign key id but still I don't have hany column that link User to Post in my DB. What I am missing?

Executing (default): CREATE TABLE IF NOT EXISTS `Posts` (`id` INTEGER NOT NULL auto_increment , `text` VARCHAR(255), `image` VARCHAR(255), `likes` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), **FOREIGN KEY (`id`)** REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;


Solution 1:[1]

First, you need to indicate the correct value in the foreignKey option, it should be a field like user_id in Post model:

User.hasMany(Post,{as: 'posts', foreignKey: 'user_id'});

Second, you need to move association definitons and sync calls (and cross-refrences of models) from model modules outside. You need to register all models and only after that to define all their associations and the last action would be calling sync methods. See the question and my answer here to get an idea how to do it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anatoly