Specifying specific fields with Sequelize (NodeJS) instead of *(使用 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) 而不是 * 指定特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Sequelize (NodeJS) 而不是 * 指定特定字段
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
