140

Is there a way to write a delete/deleteAll query like findAll?

For example I want to do something like this (assuming MyModel is a Sequelize model...):

MyModel.deleteAll({ where: ['some_field != ?', something] })
    .on('success', function() { /* ... */ });
lakenen
  • 3,436
  • 5
  • 27
  • 39

14 Answers14

334

For anyone using Sequelize version 3 and above, use:

Model.destroy({
    where: {
        // criteria
    }
})

Sequelize Documentation - Sequelize Tutorial

Alvin
  • 920
  • 3
  • 9
ncksllvn
  • 5,699
  • 2
  • 21
  • 28
  • It's a pretty old question so at the time I guess Sequelize didn't have a destroy method surprisingly – ncksllvn Jun 16 '16 at 18:39
  • 3
    Fair enough; though because this is the first search result on Google, and people are also discouraged from asking questions that have already been asked it seems like the accepted answer should get updated... but that's probably more of a site wide issue. – Rojuinex Jun 19 '16 at 20:14
  • 1
    I'm wondering sequelize documentation doesn't give, this much pretty easy coding sample... Any one can understand this. Thank you ncksllvn. You save my time... – weeraa Mar 05 '18 at 17:29
  • How do you handle if the id is an invalid id? – Rod Aug 25 '18 at 18:24
24

I've searched deep into the code, step by step into the following files:

https://github.com/sdepold/sequelize/blob/master/test/Model/destroy.js

https://github.com/sdepold/sequelize/blob/master/lib/model.js#L140

https://github.com/sdepold/sequelize/blob/master/lib/query-interface.js#L207-217

https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js

What I found:

There isn't a deleteAll method, there's a destroy() method you can call on a record, for example:

Project.find(123).on('success', function(project) {
  project.destroy().on('success', function(u) {
    if (u && u.deletedAt) {
      // successfully deleted the project
    }
  })
})
alessioalex
  • 62,577
  • 16
  • 155
  • 122
20

This example shows how to you promises instead of callback.

Model.destroy({
   where: {
      id: 123 //this will be your id that you want to delete
   }
}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted
  if(rowDeleted === 1){
     console.log('Deleted successfully');
   }
}, function(err){
    console.log(err); 
});

Check this link out for more info http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger

Hisham Haniffa
  • 449
  • 5
  • 7
18

Don't know if the question is still relevant but I have found the following on Sequelize's documentation.

User.destroy('`name` LIKE "J%"').success(function() {
    // We just deleted all rows that have a name starting with "J"
})

http://sequelizejs.com/blog/state-of-v1-7-0

Hope it helps!

cgiacomi
  • 4,629
  • 6
  • 27
  • 33
  • 2
    For reference, this is defined in [lib/model.js](https://github.com/sequelize/sequelize/blob/51ce2fb7f60359fc04814afe6779bb0ada41b18d/lib/model.js#L1272), and you don't have to use a string. You can use any sort of `where` object (e.g. `{someId: 123}`). – Domi Jun 16 '14 at 12:55
13

In new version, you can try something like this

function (req,res) {    
        model.destroy({
            where: {
                id: req.params.id
            }
        })
        .then(function (deletedRecord) {
            if(deletedRecord === 1){
                res.status(200).json({message:"Deleted successfully"});          
            }
            else
            {
                res.status(404).json({message:"record not found"})
            }
        })
        .catch(function (error){
            res.status(500).json(error);
        });
todgru
  • 139
  • 2
  • 12
Adiii
  • 54,482
  • 7
  • 145
  • 148
7

Here's a ES6 using Await / Async example:

    async deleteProduct(id) {

        if (!id) {
            return {msg: 'No Id specified..', payload: 1};
        }

        try {
            return !!await products.destroy({
                where: {
                    id: id
                }
            });
        } catch (e) {
            return false;
        }

    }

Please note that I'm using the !! Bang Bang Operator on the result of the await which will change the result into a Boolean.

li x
  • 3,953
  • 2
  • 31
  • 51
2

I wrote something like this for Sails a while back, in case it saves you some time:

Example usage:

// Delete the user with id=4
User.findAndDelete(4,function(error,result){
  // all done
});

// Delete all users with type === 'suspended'
User.findAndDelete({
  type: 'suspended'
},function(error,result){
  // all done
});

Source:

/**
 * Retrieve models which match `where`, then delete them
 */
function findAndDelete (where,callback) {

    // Handle *where* argument which is specified as an integer
    if (_.isFinite(+where)) {
        where = {
            id: where
        };
    }

    Model.findAll({
        where:where
    }).success(function(collection) {
        if (collection) {
            if (_.isArray(collection)) {
                Model.deleteAll(collection, callback);
            }
            else {
                collection.destroy().
                success(_.unprefix(callback)).
                error(callback);
            }
        }
        else {
            callback(null,collection);
        }
    }).error(callback);
}

/**
 * Delete all `models` using the query chainer
 */
deleteAll: function (models) {
    var chainer = new Sequelize.Utils.QueryChainer();
    _.each(models,function(m,index) {
        chainer.add(m.destroy());
    });
    return chainer.run();
}

from: orm.js.

Hope that helps!

mikermcneil
  • 11,141
  • 5
  • 43
  • 70
2

I have used sequelize.js, node.js and transaction in belowcode and added proper error handling if it doesn't find data it will throw error that no data found with that id

deleteMyModel: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let feature = await sequelize.MyModel.findOne({
            where: {
                id: req.body.id
            }
        })

        if (feature) {
            let feature = await sequelize.MyModel.destroy({
                where: {
                    id: req.body.id
                }
            });

            let result = error.OK;
            result.data = MyModel;
            return res.status(200).send(result);

        } else {
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        return res.status(500).send(error.SERVER_ERROR);
    });
}
Aryan
  • 3,338
  • 4
  • 18
  • 43
  • Shouldn't you add `transaction: t1` into the options of `findOne`, and `destroy` functions? – Farzan Jun 05 '22 at 17:52
2

Sequelize methods return promises, and there is no delete() method. Sequelize uses destroy() instead.

Example

Model.destroy({
  where: {
    some_field: {
      //any selection operation
      // for example [Op.lte]:new Date()
    }
  }
}).then(result => {
  //some operation
}).catch(error => {
  console.log(error)
})

Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy

simmer
  • 2,639
  • 1
  • 18
  • 22
1

Simple DELETE queries Delete queries also accept the where option, just like the read queries shown above.

// Delete everyone named "Jane"
await User.destroy({
  where: {
    firstName: "Jane"
  }
});

To destroy everything the TRUNCATE SQL can be used:

// Truncate the table
await User.destroy({
  truncate: true
});
MD SHAYON
  • 7,001
  • 45
  • 38
0
  1. the best way to delete a record is to find it firstly (if exist in data base in the same time you want to delete it)
  2. watch this code
const StudentSequelize = require("../models/studientSequelize");
const StudentWork = StudentSequelize.Student;

const id = req.params.id;
    StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5
    .then( resultToDelete=>{
        resultToDelete.destroy(id); // when i find the result i deleted it by destroy function
    })
    .then( resultAfterDestroy=>{
        console.log("Deleted :",resultAfterDestroy);
    })
    .catch(err=> console.log(err));
bahri noredine
  • 731
  • 9
  • 15
0

Delete all, no conditions:

Model.destroy({
    truncate: true,
})
S..
  • 5,511
  • 2
  • 36
  • 43
0

Example Using an API method

exports.deleteSponsor = async (req, res) => {
  try {

using conditions like userid,eventid and sponsorid

    const { userId } = req.body;
    const { eventId } = req.body;
    const { sponsorId } = req.body;

checking exist or not

    if (!sponsorId)
      return res
        .status(422)
        .send({ message: "Missing Sponsor id in parameters" });
`checking in db too`

    const sponsorDetails = await Sponsor.findAll({
      where: { [Op.or]: [{ id: sponsorId }] },
    });

    if (sponsorDetails.length === 0) {
      return res.status(422).send({ message: "Sponsor id not exist" });
    } else {
      await Sponsor.destroy({

where clause as per your requirements you can change

        where: {
          id: sponsorId,
          userId: userId,
          eventId: eventId,
        }
      });
      return res
        .status(201)
        .send({ message: "Sponsor deleted successfully" });
    }
  } catch (err) {
    console.log(err);
    customGenericException(err, res);
  }
};
Pallav Chanana
  • 617
  • 5
  • 10
0

You can use like below to delete All rows.

general_category.destroy({ truncate: true, where: {} })
        
Ninja Master
  • 126
  • 3