i am building resful api with node js and sequelize (mysql).
i have two models with (event) has many (users).
for creating event with models i am doing this :
add(req, res) {
return event.create(
{
name: req.body.name,
users: req.body.users,
},
{
include: [
{
model: User,
as: "users",
},
],
}
)
it's working fine .
but when i want to update i have big issue here. for example my current events looks like :
"events" : [
{
"id" : 1 ,
"name" :"name"
"users" :[
{
"id" :1 ,
"name" :"name1",
},
{
"id" :2 ,
"name" :"name2",
}
]
}]
what i want to achieve : i want to update users : if the id of user exists in the request i want to update the user ,but if the id doesn't exists in the request i want to delete do user.
how i can do that in sequelize and node js .i'm stack here.
Show your router where you try to handle that logic. When you say that user exists do you mean user exists at all or only belongs to requested event, please be more specific!!!
// lets say you want to update users of event id=1
const event = await Event.findByPk(1)
// you can get users belonging to event by association mixins
const users = await event.getUsers()
// loop through users to update them
for (let i=0; i < users.length; i++) {
// put your logic to make changes to users
if (users[i].getDataValue('id') == 1) {
await event.removeUser(users[i])
}
}