ddunny / repo1

repo1
0 stars 0 forks source link

How to establish a one-to-many relationship using sequelize in Nodejs? #3

Open ddunny opened 2 months ago

ddunny commented 2 months ago

I have a model called users.model.js

const postsModel = require("../Posts/posts.model");

const User = sequelize.define(
    'User',
    {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            allowNull: false,
            primaryKey: true
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false,
        },
    },
    {
        freezeTableName: true,
        hooks: {
            beforeCreate: (user) => {
                user.password = bcrypt.hashSync(user.password, 10)
            }
        },
    },
);

User.hasMany(postsModel,{foreignKey:"createdBy",as:"posts"});

User.sync({ force: true }).then(()=>{
    console.log("Synced user model with DB")
  }).catch((err)=>{
    console.log(err)
  });

module.exports = User;

And another model called posts.model.js

const usersModel = require("../Users/users.model");

const Post = sequelize.define(
    'Post',
    {
        title: {
            type: DataTypes.STRING,
            allowNull:false,
        },
        desc: {
            type: DataTypes.TEXT,
            allowNull:false,
        },
        createdBy: {
            type: DataTypes.UUID,
            references:{
                model:"User",
                key:"id"
            },
            allowNull:false,
        },
    },
    { freezeTableName: true }
);

Post.belongsTo(usersModel);

Post.sync({ force: true }).then(()=>{
    console.log("Synced post model with DB")
  }).catch((err)=>{
    console.log(err)
  });

module.exports = Post;

I am trying to populate all the posts that belongs to a user using below code:

const foundUser = await usersModel.findOne(
            {
                where:
                    { username: req.body.username },
                include: [{ model: sequelize.model("Post") }],
            });

But i am getting this error: Error: Post.belongsTo called with something that's not a subclass of Sequelize.Model

I tried following:

Post.belongsTo(sequelize.model("User")) - This is throwing Error: User has not been defined. Post.belongsTo("User") - This is throwing Error: Post.belongsTo called with something that's not a subclass of Sequelize.Model I also tried using Post.associate but that method is not available in the version of sequelize i am using (6.37.3). I want to populate all posts related to the user based on user.id.