Javascript Sequelize.js 删除查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8402597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:52:37  来源:igfitidea点击:

Sequelize.js delete query?

javascriptnode.jssequelize.js

提问by lakenen

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

有没有办法编写像 findAll 这样的 delete/deleteAll 查询?

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

例如我想做这样的事情(假设 MyModel 是一个 Sequelize 模型......):

MyModel.deleteAll({ where: ['some_field != ?', something] })
    .on('success', function() { /* ... */ });

回答by ncksllvn

For anyone using Sequelize version 3 and above, use:

对于使用 Sequelize 3 及以上版本的任何人,请使用:

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

Sequelize Documentation- Sequelize Tutorial

Sequelize 文档- Sequelize 教程

回答by alessioalex

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/test/Model/destroy.js

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

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/query-interface.js#L207-217

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

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:

没有 deleteAll 方法,有一个可以在记录上调用的 destroy() 方法,例如:

Project.find(123).on('success', function(project) {
  project.destroy().on('success', function(u) {
    if (u && u.deletedAt) {
      // successfully deleted the project
    }
  })
})

回答by cgiacomi

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

不知道这个问题是否仍然相关,但我在 Sequelize 的文档中发现了以下内容。

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

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

Hope it helps!

希望能帮助到你!

回答by Hisham Haniffa

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

查看此链接以获取更多信息 http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger

回答by Adiii

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

回答by li x

Here's a ES6 using Await / Async example:

这是一个使用 Await / Async 的 ES6 示例:

    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.

请注意,我!!在 await 的结果上使用Bang Bang 运算符,这会将结果更改为布尔值。

回答by mikermcneil

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

不久前我为 Sails 写了这样的东西,以防它为您节省一些时间:

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.

来自:orm.js

Hope that helps!

希望有帮助!

回答by bahri noredine

  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
  1. 删除记录的最好方法是先找到它(如果在数据库中同时存在您要删除它)
  2. 看这个代码
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));
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));