I have implemented a setup in my postgresql database where users can follow each other by using a through table.
as: 'follower',
through: 'follow',
foreignKey: 'follower_id'
})
User.belongsToMany(User, {
as: 'following',
through: 'follow',
foreignKey: 'following_id'
})
Here is the structure of the table:
| created_at | updated_at | follower_id | following_id |
|------------|------------|-------------|--------------|
| | | | |
When I make a get request like this:
userRouter.get('/:user_id/followers', async (req, res) => {
try {
const user = await User.findOne({
where: {
id: req.params.user_id
},
include: [
{
model: User,
as: 'follower',
through: { attributes: [] }
}
]
})
res.send(user)
} catch (error) {
console.log(error)
}
})
I receive a result like this:
{
"id": 1,
"firstName": "John",
"lastName": "Smith",
"username": "tester",
"profileImage": null,
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e4f5e3e4f5e2d0fdf1f9fcbef3fffd">[email protected]</a>",
"password": "$2b$12$h2rVqmxgsGxTOVgq3aII5uCuRcSN0TZZ6lwZgRRHCaOhu98K3AKbe",
"skills": [
"React",
"Python",
"Mongo"
],
"createdAt": "2019-07-07T23:38:07.730Z",
"updatedAt": "2019-07-07T23:38:07.730Z",
"follower": []
}
Now I am looking for guidance on how to use post or put requests to add new entries to this table.