使用 Sequelize (NodeJS) 而不是 * 指定特定字段 [英] Specifying specific fields with Sequelize (NodeJS) instead of *

查看:24
本文介绍了使用 Sequelize (NodeJS) 而不是 * 指定特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我在 NodeJS 中有一个项目,我将 Sequelize 用于 MySQL ORM.这件事非常有效,但是我试图弄清楚是否有一种方法可以指定基于查询返回哪些字段,或者是否有一种方法可以在某处执行 .query() .

Alright so I have a project in NodeJS where I'm utilizing Sequelize for a MySQL ORM. The thing works fantastically however I'm trying to figure out if there is a way to specify what fields are being returned on a query basis or if there's even a way just to do a .query() somewhere.

例如,在我们的用户数据库中,记录和列的数量可能非常多.在这种情况下,我只需要返回三列,因此只获取这些列会更快.但是,Sequelize 只是在表中查询所有*"以尽可能地满足完整的对象模型.这是我想在应用程序的这个特定区域绕过的功能.

For example in our user database there can be ridiculous amounts of records and columns. In this case I need to return three columns only so it would be faster to get just those columns. However, Sequelize just queries the table for everything "*" to fulfill the full object model as much as possible. This is the functionality I'd like to bypass in this particular area of the application.

推荐答案

您必须将属性指定为传递给 findAll() 的对象中的属性:

You have to specify the attributes as a property in the object that you pass to findAll():

Project.findAll({attributes: ['name', 'age']}).on('success', function (projects) {
  console.log(projects);
});

我是如何发现这个的:

这里首先调用查询:https://github.com/sdepold/sequelize/blob/master/lib/model-definition.js#L131
然后在这里构造:https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js#L56-59

这篇关于使用 Sequelize (NodeJS) 而不是 * 指定特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆