I am trying to delete my forum and I would like that when I delete the forum all the members who are in the forum are also deleted here is the code of the controllers
module.exports.deleteGroup = async (req, res, next) => {
const token = req.cookies.jwt;
const decoded = jwtAuth.verify(token, process.env.TOKEN_SECRET);
const userTokenId = decoded.id;
try {
const { id } = req.params;
const currentUser = await User.findByPk(userTokenId);
if (!currentUser) return res.status(404).json('You must be logged in to make this request');
const forum = await Forum.findOne({ where: { id } });
if (!forum) return res.status(404).json("This forum does not exist please try again!");
if (forum.createByUserId === currentUser.id || currentUser.isAdmin) {
const deleteForum = await Forum.destroy({ where: { id } });
if (deleteForum) {
const deleteMembers = await ForumMember.destroy({ where: {} });
return res.status(200).json(`The forum ${forum.name} has been deleted`);
}
else {
return res.status(401).json(`You are not authorized to delete this forum`)
}
}
} catch (error) {
res.status(500).json(error.message)
}
}
My associations
//Users
models.User.belongsToMany(models.Forum, {
through: models.ForumMember,
foreignKey: 'userId',
otherKey: 'forumId'
});
//Forums
models.Forum.belongsToMany(models.User, { through: models.ForumMember, foreignKey: 'forumId', otherKey: 'userId', });
//ForumMember
models.ForumMember.belongsTo(models.Forum, {
foreignKey: 'forumId',
as: 'groups'
});
models.ForumMember.belongsTo(models.User, {
foreignKey: 'userId',
as: 'members'
});
}
};
ForumMember.init({
forumId: {
type: DataTypes.INTEGER,
references: {
model: 'Forum',
key: 'id'
},
},
userId: {
type: DataTypes.INTEGER,
references: {
model: 'User',
key: 'id'
},
Now when I execute on PostMan I get this response: "Cannot delete or update a parent row: a foreign key constraint fails (groupomania_database_development.forummembers, CONSTRAINT forummembers_ibfk_1 FOREIGN KEY (forumId) REFERENCES forums (id))" I think I have a problem with my associations. I'm a newbie on sequelize and I would like to have your help please
First, you need to delete child records in junk table and the final step would be the deletion of a forum.
Second, you didn't indicate a condition in ForumMember.destroy so Sequelize tries to delete all rows in ForumMeber regardless what forum they belong to.
const deleteMembers = await ForumMember.destroy({ where: { forumId: id } });
const deleteForum = await Forum.destroy({ where: { id } });
if (deleteForum) {
return res.status(200).json(`The forum ${forum.name} has been deleted`);
}
Third, to avoid inconsistent data in DB you need to use transactions if you make several modifications:
await sequelize.transaction(async (tr) => {
const deleteMembers = await ForumMember.destroy({ where: { forumId: id }, transaction: tr });
const deleteForum = await Forum.destroy({ where: { id }, transaction: tr });
...
});