Я нашел ответ после некоторой обработки.
При публикации нового подписчика возникла проблема: он перезаписывал существующие записи.
Вот как я устанавливаю связи:
const Follower = db.define('follower', {
follower_id: {
primaryKey: true,
type: Sequelize.INTEGER
}
})
Follower.belongsTo(User, {
as: 'user',
through: 'follower',
foreignKey: 'follower_id'
})
User.hasMany(Follower, { as: 'followers' })
Мой маршрут получения:
userRouter.get('/:user_id/followers', async (req, res) => {
try {
const user = await User.findOne({
where: {
id: req.params.user_id
},
include: [
{
model: Follower,
as: 'followers',
include: [
{
model: User,
as: 'user'
}
]
}
]
})
res.send(user)
} catch (error) {
throw error
}
})
почтовый маршрут:
userRouter.post('/:user_id/follow/:follower_id', async (req, res) => {
try {
const user = await User.findByPk(req.params.user_id)
if (user) {
if (user.id.toString() === req.params.follower_id) {
res.status(400).json({ err: 'You cannot follow yourself' })
} else {
const following = await Follower.findOrCreate({
where: {
userId: req.params.user_id,
follower_id: req.params.follower_id
}
})
res.send(following)
}
}
} catch (error) {
throw error
}
})
Теперь работает как шарм:
follower_id | created_at | updated_at | user_id
-------------+----------------------------+----------------------------+---------
2 | 2019-07-07 23:36:06.696-04 | 2019-07-07 23:36:06.696-04 | 1
3 | 2019-07-07 23:36:22.498-04 | 2019-07-07 23:36:22.498-04 | 1
данные изAPI:
{
"id": 1,
"firstName": "John",
"lastName": "Smith",
"username": "tester",
"profileImage": null,
"email": "tester@mail.com",
"password": "$2b$12$0Ir/1zWRPvx3MWRjq6l85.z35QyCPwDqX7TyhAeWZHLx75RmGzlKS",
"skills": [
"React",
"Python",
"Mongo"
],
"createdAt": "2019-07-08T03:36:00.262Z",
"updatedAt": "2019-07-08T03:36:00.262Z",
"followers": [
{
"follower_id": 2,
"createdAt": "2019-07-08T03:36:06.696Z",
"updatedAt": "2019-07-08T03:36:06.696Z",
"userId": 1,
"user": {
"id": 2,
"firstName": "Jane",
"lastName": "Doe",
"username": "test",
"profileImage": null,
"email": "test@mail.com",
"password": "$2b$12$pxg9ssYtSIZm3TPcYDzjnOZApaFjXWPypM8et1m5nSPZeH1voGVHO",
"skills": [
"HTML",
"Css",
"React"
],
"createdAt": "2019-07-08T03:36:00.519Z",
"updatedAt": "2019-07-08T03:36:00.519Z"
}
},
{
"follower_id": 3,
"createdAt": "2019-07-08T03:36:22.498Z",
"updatedAt": "2019-07-08T03:36:22.498Z",
"userId": 1,
"user": {
"id": 3,
"firstName": "Jackie",
"lastName": "Legs",
"username": "test3",
"profileImage": null,
"email": "test3@mail.com",
"password": "$2b$12$V0UgOVxB.c5/gbuUIqvvW.cnWqZjsqLUnHCgoT4zwzFtBPucgRAl2",
"skills": [
"HTML",
"Css"
],
"createdAt": "2019-07-08T03:36:00.758Z",
"updatedAt": "2019-07-08T03:36:00.758Z"
}
}
]
}