javascriptnode.jssequelize.jsinstancedestroy

Sequelize destroy command


I'm trying delete one record, via destroy method of an instance.

const memCustomers = await Customers.findAll({ limit: 10 })

for (const customer of memCustomers ) {
    //do things
    await customer.destroy()
}

But when i use this command it delete all records in table customers, and when i add "where" argument for destroy method, nothing change...

I set logging equal true... and it show a "delete from table" without "where".


Solution

  • You have two options:

    1. Filter your customers on the app side
    const customers = await Customers.findAll({ where: …, limit: … })
    
    Promise.all(customers.filter( … ).map(customer => customer.destroy()))
    
    1. Call your database again
    const customers = await Customers.findAll({ where: …, limit: … })
    
    await Customers.destroy({ where: … })
    

    This highly depends on the number of entries but I would always recommend doing the filtering on the database level