0

I'm building an app in express and I'm using postgres and sequelize for ORM. I have two models, User and Post.

In my user.js and post.js files I have:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('users', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ""
    },

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('posts', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: true
    },
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ""
    },

I imported those two models and I made the following associations:

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

Post.belongsTo(User, { foreignKey: 'user_id' });

I am trying to render all the posts done by a user, but I'm probably missing something.

In my routes I can get the correct user but I don't know how to proceed.

router.route('/:id').get(async (req, res) => {
  const user = await User.findById(req.params.id);
  console.log(user);
  res.send(user);
})

Thanks!

1 Answer 1

1

findById does not support the associated model ,

User.findById(req.params.id);

You can change findById to findOne and include model like this ,

User.findOne({
    where : { id : req.params.id },
    include : {
        model : Post
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.