[javascript] Sequelize.js delete query?

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() { /* ... */ });

This question is related to javascript node.js sequelize.js

The answer is


For anyone using Sequelize version 3 and above, use:

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

Sequelize Documentation - Sequelize Tutorial


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


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

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


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

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

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.


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!


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

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!


Delete all, no conditions:

Model.destroy({
    truncate: true,
})

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to sequelize.js

sequelize findAll sort order in nodejs Prevent Sequelize from outputting SQL to the console on execution of query? How to auto generate migrations with Sequelize CLI from Sequelize models? Sequelize, convert entity to plain object Sequelize OR condition object How to make join queries using Sequelize on Node.js Sequelize.js delete query? How to update a record using sequelize for node?