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
P粉5233350262024-02-26 16:27:45
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 the author
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.
static async deleteUserById(req, res) { const id = req.params.id; try { const user = await User.remove({ // O/p WriteResult({ "nRemoved" : 1 }) // where: { no need of where clause // id: id, //}, "_id": id }); // once you remove the user // remove articles const articles = await Articles.remove({ 'author': 'pass_author_id' }); // do your things } catch(e) { console.log(error); } }