Home > other >  how to delete user related article in sequelize?
how to delete user related article in sequelize?

Time:06-22

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 do I delete all articles created by user when the user deletes the account?

I have the following function to delete the 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'm coming from mongodb to mysql and I'm kind of lost in relationships

CodePudding user response:

Your Article model doesn't have any relation to the User as I see it only has a user name with it. You can create a new collection for Author and when you create a new article saving the Author _id in the author field is fine.

Now, when you delete the user, you can query Article collection based on the Author key and remove it. However, once removed you won't be able to get back the articles.


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);
    }
}

CodePudding user response:

I managed to solve it by adding the following code from the article model

User.hasMany(Article, {
    onDelete: "CASCADE",
});

My mistake was that I was trying to use this function inside the user model

  • Related