I have an article model where each article is related to a user:
const Articles = db.define("Articles", { title: { type: DataTypes.STRING, allowNull: false, }, description: { type: DataTypes.STRING, allowNull: false, }, img_url: { type: DataTypes.STRING, allowNull: false, }, author: { type: DataTypes.STRING, allowNull: false, }, }); Articles.belongsTo(User); module.exports = Articles;
How to delete all articles created by a user when they delete their account?
I have the following function to delete a user:
static async deleteUserById(req, res) { const id = req.params.id; const user = await User.findOne({ where: { id: id, }, }); if (!user) { res.status(404).json({ msg: "User not found!" }); return; } try { await User.destroy({ where: { id: id, }, }); res.status(200).json({ msg: "Account successfully deleted!" }); } catch (msg) { res.status(500).json({ msg: "Oops... an error has occurred!" }); } }
I moved from mongodb to mysql and I'm a bit lost in relationships
Your post model doesn't have anything to do with users as I see it only has a username. You can create a new collection for authors and just save the author
_id
in theauthor
field when you create a new article.Now when you delete a user you can query the collection of articles based on the author key and delete them. However, once deleted, you will not be able to get the articles back.