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!