Sequelize.js删除查询?
有没有办法写一个像findAll一样的delete / deleteAll查询?
例如,我想要做这样的事情(假设MyModel是一个Sequelize模型…):
MyModel.deleteAll({ where: ['some_field != ?', something] }) .on('success', function() { /* ... */ });
对于使用Sequelize版本3及以上的人,请使用:
Model.destroy({ where: { // criteria } })
Sequelize文档 – Sequelize教程
我已深入search代码,一步一步进入以下文件:
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
我发现:
没有deleteAll方法,可以在logging上调用destroy()方法,例如:
Project.find(123).on('success', function(project) { project.destroy().on('success', function(u) { if (u && u.deletedAt) { // successfully deleted the project } }) })
不知道问题是否仍然相关,但我在Sequelize的文档中find了以下内容。
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
希望能帮助到你!
这个例子显示了你如何承诺,而不是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); });
查看此链接了解更多信息http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger
我为Sails写了一些这样的东西,以免浪费一些时间:
用法示例:
// 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 });
资源:
/** * 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(); }
来自: orm.js 。
希望有所帮助!
在新版本中,你可以尝试一些这样的事情
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); });