admin管理员组

文章数量:1129459

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

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() { /* ... */ });
Share Improve this question asked Dec 6, 2011 at 15:40 lakenenlakenen 3,4965 gold badges29 silver badges41 bronze badges
Add a comment  | 

14 Answers 14

Reset to default 338

For anyone using Sequelize version 3 and above, use:

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

Sequelize Documentation - Sequelize Tutorial

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

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!

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

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.

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!

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

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

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

Delete all, no conditions:

Model.destroy({
    truncate: true,
})

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

You can use like below to delete All rows.

general_category.destroy({ truncate: true, where: {} })
        

本文标签: javascriptSequelizejs delete queryStack Overflow