Sequelize.js delete query?

Javascriptnode.jssequelize.js

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

For anyone using Sequelize version 3 and above, use:

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

Sequelize Documentation - Sequelize Tutorial

Solution 2 - Javascript

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

Solution 3 - Javascript

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!

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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!

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

Delete all, no conditions:

Model.destroy({
	truncate: true,
})

Solution 12 - Javascript

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

Solution 13 - Javascript

You can use like below to delete All rows.

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

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlakenenView Question on Stackoverflow
Solution 1 - JavascriptncksllvnView Answer on Stackoverflow
Solution 2 - JavascriptalessioalexView Answer on Stackoverflow
Solution 3 - JavascriptcgiacomiView Answer on Stackoverflow
Solution 4 - JavascriptHisham HaniffaView Answer on Stackoverflow
Solution 5 - JavascriptAdiiiView Answer on Stackoverflow
Solution 6 - Javascriptli xView Answer on Stackoverflow
Solution 7 - JavascriptmikermcneilView Answer on Stackoverflow
Solution 8 - JavascriptAryanView Answer on Stackoverflow
Solution 9 - Javascriptdamith anuradhaView Answer on Stackoverflow
Solution 10 - Javascriptbahri noredineView Answer on Stackoverflow
Solution 11 - JavascriptS..View Answer on Stackoverflow
Solution 12 - JavascriptPallav ChananaView Answer on Stackoverflow
Solution 13 - Javascriptuser2693349View Answer on Stackoverflow
Solution 14 - JavascriptMD SHAYONView Answer on Stackoverflow