使用Sequelize(NodeJS)而非*指定特定字段 [英] Specifying specific fields with Sequelize (NodeJS) instead of *
问题描述
好的,所以我在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
The query is first called here: https://github.com/sdepold/sequelize/blob/master/lib/model-definition.js#L131
Then gets constructed here: https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js#L56-59
这篇关于使用Sequelize(NodeJS)而非*指定特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!