Node js - Sequelize - Destroy several selected ids by one push

Viewed 19

I have issue with multi delete:

   export const deleteProducts = async (req, res) => {
  try {
    const ids = req.params.ids
  
    await Product.destroy({
      where: {
        id: ids
      }
    });
    res.json({
      message: "ProductS Deleted",
    });
  } catch (error) {
    res.json({ message: error.message });
  }
};

when I send request with ID's array to this function for example

http://localhost:5000/products/deleteByIds/535,536.537

function delete from mySQL only one first ID, But in log I see this:

Executing (default): DELETE FROM `products` WHERE `id` IN ('535,536,537')

when I try this like that -

export const deleteProducts = async (req, res) => {
      try {
        const ids = [535,536,537]
      
        await Product.destroy({
          where: {
            id: ids
          }
        });
        res.json({
          message: "ProductS Deleted",
        });
      } catch (error) {
        res.json({ message: error.message });
      }
    };

everything working

Executing (default): DELETE FROM `products` WHERE `id` IN (535, 536, 537)

where I make mistake?

1 Answers

req.params.ids is of type string.

You need to put the ids in an array, then perform the delete operation

you can convert the ids in an array following ways

const ids = req.params.ids.split(',');

Hope it'll fix your issue.

Related