Sequelize: How to delete user related articles?
P粉212971745
P粉212971745 2024-02-25 17:24:16
0
1
462

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粉212971745
P粉212971745

reply all(1)
P粉523335026

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);
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template