Repository navigation
Description
What are you doing?
I have a project that uses Sequelize as ORM. I need the attribute names returned in snake_case, but although I've specified underscored: true in my model definition, the attributes are returned in camelCase instead. (The DB tables are in snake_case, as expected).
I'm also using Sequelize 4.x in a few other projects and it doesn't affect it afaik.
Can be the same reason as here: #10581 (but it was closed because of not proper issue format).
I can provide more details if needed.
Sequelize config:
const Sequelize = require('sequelize');
const getSequelize = () => new Sequelize(config.postgres.database, config.postgres.username, config.postgres.password, {
host: config.postgres.host,
port: config.postgres.port,
dialect: 'postgres',
logging: sql => logger.debug(sql)
});
let sequelize = getSequelize();
exports.sequelize = sequelize;
exports.Sequelize = Sequelize;Model definition
const { Sequelize, sequelize } = require('../lib/sequelize');
const Code = sequelize.define('code', {
value: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: '',
validate: {
notEmpty: { msg: 'Code should be set.' },
},
},
integration_id: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: '',
validate: {
notEmpty: { msg: 'Integration ID should be set.' },
},
},
claimed_by: {
type: Sequelize.INTEGER
}
}, { underscored: true, tableName: 'codes' });
module.exports = Code;Endpoint using this model (I have 2 models but I provide only one for the case of simplicity):
exports.getMyCodes = async (req, res) => {
const myCodes = await Code.findAll({
where: {
claimed_by: req.user.id
},
include: [Integration],
order: [
['updated_at', 'DESC'],
]
});
return res.json(myCodes);
};What do you expect to happen?
Everything returned in snake_case
What is actually happening?
The server response (note the integrationId, createdAt and updatedAt are in camelCase):
[{
"id": 7,
"value": "2",
"integration_id": 2,
"claimed_by": 1,
"createdAt": "2019-04-28T19:14:51.641Z",
"updatedAt": "2019-04-28T19:16:24.259Z",
"integrationId": 2,
"integration": {
"id": 2,
"name": "Help",
"code": "flixbus",
"quota_period": "month",
"quota_amount": 3,
"description": "**I need somebody**",
"createdAt": "2019-04-28T19:14:15.164Z",
"updatedAt": "2019-04-28T19:14:15.164Z"
}
}, {
"id": 6,
"value": "1",
"integration_id": 2,
"claimed_by": 1,
"createdAt": "2019-04-28T19:14:51.641Z",
"updatedAt": "2019-04-28T19:14:55.130Z",
"integrationId": 2,
"integration": {
"id": 2,
"name": "Help",
"code": "flixbus",
"quota_period": "month",
"quota_amount": 3,
"description": "**I need somebody**",
"createdAt": "2019-04-28T19:14:15.164Z",
"updatedAt": "2019-04-28T19:14:15.164Z"
}
}, {
"id": 1,
"value": "one",
"integration_id": 1,
"claimed_by": 1,
"createdAt": "2019-04-28T19:01:07.660Z",
"updatedAt": "2019-04-28T19:12:03.643Z",
"integrationId": 1,
"integration": {
"id": 1,
"name": "test",
"code": "test",
"quota_period": "month",
"quota_amount": 1,
"description": "test",
"createdAt": "2019-04-28T19:01:01.724Z",
"updatedAt": "2019-04-28T19:01:01.724Z"
}
}]It only affects Sequelize 5.x, not 4.x
I've tried to downgrade to sequelize and sequelize-cli 4.x, and it works as expected:
$ npm ls | grep sequelize
├─┬ [email protected]
├─┬ [email protected]and the server response (with the exact same example above, only thing changed was downgrading sequelize and sequelize-cli packages) looks like this:
[{
"id": 8,
"value": "3",
"integration_id": 2,
"claimed_by": 1,
"created_at": "2019-04-28T19:14:51.641Z",
"updated_at": "2019-04-29T16:52:31.198Z",
"integration": {
"id": 2,
"name": "Help",
"code": "flixbus",
"quota_period": "month",
"quota_amount": 3,
"description": "**I need somebody**",
"created_at": "2019-04-28T19:14:15.164Z",
"updated_at": "2019-04-28T19:14:15.164Z"
}
}]Environment
Dialect: postgres, also can be that it affects all of them.
Dialect library version: pg 7.10.0
Database version: psql 10
Sequelize version: 5.7.6
Node Version: 10.2.1
OS: MacOS Mojave 10.14.4 (x64)
Tested with latest release: yes, with 5.7.6 (latest NPM release afaik)
Activity
serge1peshcoff commentedon Apr 28, 2019
Also, this can help probably, here's one of my SQL log lines, seems like it queries the right fields but maps them to wrong values (
camelCaseones instead ofsnake_caseones):aaronovz1 commentedon Apr 29, 2019
I am seeing the same problem. My issue seems to be that only association/foreign key variables are not becoming snake_case (same as #10581).
serge1peshcoff commentedon Apr 29, 2019
@aaronovz1 so the timestamps are returned in
snake_casefor you? Also, what version of Sequelize are you using? (It can be that it affects latest Sequelize versions only, just want to check it).aaronovz1 commentedon Apr 29, 2019
@serge1peshcoff actually the timestamps are camelCase too. Looks like we have the exact same problem. I am running the Sequelize 5.7.6.
serge1peshcoff commentedon Apr 29, 2019
@aaronovz1 then we are on the same page and I'm not only one facing this :D
Btw, I've tried to downgrade to
sequelizeandsequelize-cli4.x, and it works as expected:and the server response (with the exact same example) looks like this:
aaronovz1 commentedon Apr 29, 2019
I only recently upgraded to 5.x, so it is definitely a bug in V5 as you've just proven by downgrading. Hope this can be fixed ASAP.
serge1peshcoff commentedon Apr 30, 2019
@aaronovz1 can you try reproducing it with other SQL dialects? I want to check if it affects only Postgres or others as well (I bet it's the latter but I can't check on my PC)
aaronovz1 commentedon Apr 30, 2019
Unfortunately I don't have the time or means to get other dialects setup at the moment.
gdanov commentedon May 6, 2019
I have the same or similar issue with sequelize v5 and postgres. My schema is smaller so I'm seing this duplication only on xxxxx_id fields (and all of them are relations). Here are few examples:
Executing (default): SELECT "users"."id", "users"."username", "users"."password_hash", "users"."account_id", "users"."account_id" AS "accountId", "account"."id" AS "account.id", "account"."name" AS "account.name", "account"."token_balance" AS "account.token_balance" FROM "users" AS "users" LEFT OUTER JOIN "account" AS "account" ON "users"."account_id" = "account"."id" WHERE "users"."account_id" = 1 LIMIT 1;Executing (default): SELECT "id", "username", "password_hash", "account_id", "account_id" AS "accountId" FROM "users" AS "users" WHERE "users"."id" = 1;this one shows that the 'camel-ization' happens only on the root entity table (request_log) while the JOIN-ed table is not affected (see report_request.account_id)
Executing (default): SELECT "request_log"."id", "request_log"."report_request_id", "request_log"."report_request_id" AS "reportRequestId", "request_log"."ts", "request_log"."user_id", "report_request"."id" AS "report_request.id", "report_request"."account_id" AS "report_request.account_id", "report_request"."was_billed" AS "report_request.was_billed", "report_request"."exec_ts" AS "report_request.exec_ts", "report_request"."ttl_ts" AS "report_request.ttl_ts", "report_request"."balance_snapshot" AS "report_request.balance_snapshot" FROM "request_log" AS "request_log" LEFT OUTER JOIN "report_request" AS "report_request" ON "request_log"."report_request_id" = "report_request"."id" WHERE "request_log"."user_id" = '1' ORDER BY "request_log"."ts" DESC LIMIT '10' OFFSET '0';Strate commentedon May 15, 2019
Almost same issue here: I use underscored: true & timestamps: true, and I expect
created_at,updated_atfields in snake_case, as it was on sequelize@4. But after upgrading to sequelize@5 fields becomescreatedAtandupdatedAtserge1peshcoff commentedon May 19, 2019
@Strate same issue as I'm facing then, it affects timestamps as well as foreign key fields. My timestamps are also in
camelCaseserge1peshcoff commentedon May 28, 2019
I've recently understood why it's failing.
Each model has an
attributesobject, where the keys are thecamelCaseattributes names, and each of these objects has afieldfield which is asnake_caseorcamelCase(depending on ifunderscoredistrueorfalse).Here is where the
fieldfield is set based onunderscoredoption:sequelize/lib/model.js
Line 1134 in 30c5ca5
In the
findAll()method where the options object for SQL query is constructed, it usesObject.keys(this.rawAttributes)which will take the names incamelCasedisregarding theunderscoredoption, here:sequelize/lib/model.js
Line 1732 in 30c5ca5
If I change it to
Object.keys(this.rawAttributes).map(key => this.rawAttributes[key].field)it should work. However it won't turn includes attributes tosnake_case.I'll most like make a PR on this either this or next week, if somebody will be faster then me I'd really appreciate it!
Strate commentedon Jun 19, 2019
@serge1peshcoff hi, would make a PR to sequelize?
serge1peshcoff commentedon Jun 19, 2019
@Strate I still haven't figure out how to do it properly, do you know how?
Strate commentedon Jun 19, 2019
@serge1peshcoff yes, use this link: master...serge1peshcoff:fix-not-respecting-underscored-in-findall
29 remaining items
liuyib commentedon Mar 14, 2021
Great, what you said is the root cause (
underscored: trueno longer honors foreign key conventions). You helped me, thanks. But, can anyone solve this problem?feeh27 commentedon Mar 19, 2021
Thanks @dzvid your configuration worked for me:
miladmeidanshahi commentedon Jun 21, 2021
https://sequelize.org/master/manual/naming-strategies.html
hwookim commentedon Aug 12, 2021
Sadly, they don't think it's a bug...
I'd probably just use
createdAt: created_atI'm on
^6.6.2vkbishu commentedon Sep 8, 2021
It's a bug and It should be fixed. As it's not a good idea to use 2 different cases for the field names.
imaccallum commentedon Nov 10, 2021
Here's what it was for me: we have a join table that uses camel case keys. There was a belongsToMany relationship in the corresponding other models that did not include
foreignKeyandotherKey. Presumably if these are not specified it defaults to the camel case version and adds it to the join table or something weird like thatliorsion commentedon Jan 14, 2022
This issue presents an even bigger problem when using TypeScript - we can't tell the compiler which field name is used because it changes..
ephys commentedon Jan 14, 2022
Maintainer here 👋. I'm trying to understand this issue a bit better. Is the issue:
created_at,user_idon the JS side, but sequelize generates camelCase,createdAt,userIdon the JS side, but havecreated_at,user_idon the database side.miladmeidanshahi commentedon Jan 15, 2022
Hi @ephys absolutely number 1 :)
ephys commentedon Jan 15, 2022
@miladmeidanshahi Thanks!
For clarity's sake, in the following text when I say:
So by default Sequelize will generate camelCase attributes and snake_case column (actually that second part is not the default yet) names because we consider it to be the standard naming conventions of JS & SQL respectively.
The
underscoredoption is only used to generate snake_case column names. As others have found out in this thread, it has no impact on attribute names.For timestamp attributes, the solution is simple enough. You can configure it per-model using the 3 timestamp options:
Or configure them for every model by configuring the Sequelize instance itself:
For foreign keys, it's trickier. There is a way to configure it per-model but there is no system wide configuration option.
To automatically generate a snake_case foreign key attribute names would require the return of an option like
underscoredAll(but with a better name).If a way to tell sequelize to generate attributes in snake_case is the desired solution, I'll keep this closed in favor of #11225 as it seems to be the relevant thread.
Let me know what you think :)
Edit:
I also think the following two RFC are relevant, at least somewhat:
createdAt,updatedAt, anddeletedAt#14303hmarat commentedon Feb 3, 2022
@ephys Thanks, worked as expected :))
yisibl commentedon Dec 28, 2022
@ephys After I override them globally, .update() will not work.
I eventually found that the solution was to call
this.changed('updated_at', true)once before.update().When I upgraded from v5 to v6, this became very buggy - when exactly did we need to call
.changed()?At the end of the day, we just want to return a snake_case timestamp and want a unified API to solve this problem once and for all.
yisibl commentedon Dec 28, 2022
#13006
ephys commentedon Dec 28, 2022
Please open a separate bug report with a reproducible example as that is not related to this thread