findAndCountAll with scope having attributes
See original GitHub issueWhen having a defaultScope defined, which contains the attributes options, the count query is messed up.
defaultScope: {
where: {
active: true
},
attributes: ['id', 'username', 'email', 'active', 'approved', 'company_id']
}
The following query is generated
SELECT "id", "username", "email", "active", "approved", "company_id", count(*) AS "count" FROM "users" AS "users" WHERE "users"."company_id" = 1 AND "users"."active" = true;
2 errors within the query. The first one, in that case, the “group by” is required. The second error is that it should normally not include the “attributes” for the count query. If I fix the first one (add the “group” option), the query runs, but “res.count” is actually returning anarray of objects from the query, with the “count” field inside.
Example :
{ count:
[ { id: 1,
username: 'Test',
email: 'test@test,cin',
active: true,
approved: true,
company_id: 1,
count: '1' },
{ id: 2,
username: 'Test2',
email: 'test@test.com',
active: true,
approved: true,
company_id: 1,
count: '1' } ],
rows:....
}
The error come from the file https://github.com/sequelize/sequelize/blob/master/lib/model.js
The findAndCountAll strips correctly the attributes options (https://github.com/sequelize/sequelize/blob/master/lib/model.js#L1604) But then within the count query, the scope is injected with the attributes and all other options that should be omitted (https://github.com/sequelize/sequelize/blob/master/lib/model.js#L1542)
I’d be happy to fix it, but I do not know what would be the best possible option to fix it. I see the following possibilities :
- Add a parameter to the count function to omit the attributes/… options after the scope is injected
- Separate the count function in 2, one which will prepare the parameters for the normal count, and the second that actually does the count. This way the findAndCount function would use directly the “count” part, as the option is already ready.
Any toughs on this ?
Thanks
Issue Analytics
- State:
- Created 8 years ago
- Comments:9 (4 by maintainers)

Top Related StackOverflow Question
@mickhansen It seems like the regression mentioned here is alive and well. This is a HUGE problem if your query uses attributes to create virtual columns, something like
SELECT some_Function_Of("table"."column") AS property WHERE property = 'foo';since during the COUNT step, the query bombs out on the error that columnpropertydoesn’t exist. Which it would, if we weren’t stripping off attributes indiscriminately here.@krisr That’s THE regression as far as i can tell 😃