如何使用 Sequelize 和 Javascript 返回查询结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16389895/
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-10-27 04:27:39  来源:igfitidea点击:

How do I return the results of a query using Sequelize and Javascript?

javascriptdatabasesequelize.js

提问by user2352919

I'm new at javascript and I've hit a wall hard here. I don't even think this is a Sequelize question and probably more so about javascript behavior.

我是 javascript 新手,在这里遇到了困难。我什至不认为这是一个 Sequelize 问题,可能更像是关于 javascript 行为。

I have this code:

我有这个代码:

sequelize.query(query).success( function(row){
            console.log(row);
    }
)

The var row returns the value(s) that I want, but I have no idea how to access them other than printing to the console. I've tried returning the value, but it isn't returned to where I expect it and I'm not sure where it goes. I want my row, but I don't know how to obtain it :(

var 行返回我想要的值,但除了打印到控制台之外,我不知道如何访问它们。我试过返回值,但它没有返回到我期望的地方,我不确定它去哪里了。我想要我的行,但我不知道如何获得它:(

回答by Brandon Buck

Using Javascript on the server side like that requires that you use callbacks. You cannot "return" them like you want, you can however write a function to perform actions on the results.

在服务器端使用 Javascript 需要你使用回调。你不能像你想要的那样“返回”它们,但是你可以编写一个函数来对结果执行操作。

sequelize.query(query).success(function(row) {
    // Here is where you do your stuff on row
    // End the process
    process.exit();
}

A more practical example, in an express route handler:

一个更实际的例子,在一个快速路由处理程序中:

// Create a session
app.post("/login", function(req, res) {
    var username = req.body.username,
        password = req.body.password;
    // Obviously, do not inject this directly into the query in the real
    // world ---- VERY BAD.
    return sequelize
      .query("SELECT * FROM users WHERE username = '" + username + "'")
      .success(function(row) {
          // Also - never store passwords in plain text
          if (row.password === password) {
              req.session.user = row;
              return res.json({success: true});
          }
          else {
              return res.json({success: false, incorrect: true});
          }
      });
});

Ignore injection and plain text password example - for brevity.

忽略注入和纯文本密码示例 - 为简洁起见。

Functions act as "closures" by storing references to any variable in the scope the function is defined in. In my above example, the correct resvalue is stored for reference per request by the callback I've supplied to sequelize. The direct benefit of this is that more requests can be handled while the query is running and once it's finished more code will be executed. If this wasn't the case, then your process (assuming Node.js) would wait for that one query to finish block all other requests. This is not desired. The callback style is such that your code can do what it needs and move on, waiting for important or processer heavy pieces to finish up and call a function once complete.

函数通过在定义函数的范围内存储对任何变量的引用来充当“闭包”。在我上面的例子中,正确的res值被存储以供我提供给 sequelize 的回调的每个请求引用。这样做的直接好处是在查询运行时可以处理更多请求,一旦完成,将执行更多代码。如果不是这种情况,那么您的进程(假设 Node.js)将等待该查询完成阻止所有其他请求。这是不希望的。回调风格是这样的,你的代码可以做它需要的事情并继续前进,等待重要的或处理繁重的部分完成并在完成后调用一个函数。

EDIT

编辑

The API for handling callbacks has changed since answering this question. Sequelize now returns a Promisefrom .queryso changing .successto .thenshould be all you need to do.

自从回答这个问题以来,处理回调的 API 已经发生了变化。Sequelize 现在返回一个Promisefrom.query所以改变.success.then应该是你需要做的。

回答by Hamza Ouaghad

According to the changelog

根据变更日志

Backwards compatibility changes:

Events support have been removed so using .on('success') or .success() is no longer supported. Try using .then() instead.

向后兼容性更改

事件支持已被删除,因此不再支持使用 .on('success') 或 .success() 。尝试使用 .then() 代替。

According this Raw queries documentationyou will use something like this now:

根据这个原始查询文档,您现在将使用如下内容:

sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
    .then(function(users) {
        console.log(users);
    });