Skip to content

Using underscored: true still returns attributes in camelCase #10857

Closed

Description

@serge1peshcoff

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

  1. serge1peshcoff commented on Apr 28, 2019

    @serge1peshcoff
    Author

    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 (camelCase ones instead of snake_case ones):

    Executing (default): SELECT "id", "name", "code", "quota_period", "quota_amount", "description", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "integrations" AS "integration";
    
  2. aaronovz1 commented on Apr 29, 2019

    @aaronovz1

    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).

  3. serge1peshcoff commented on Apr 29, 2019

    @serge1peshcoff
    Author

    @aaronovz1 so the timestamps are returned in snake_case for you? Also, what version of Sequelize are you using? (It can be that it affects latest Sequelize versions only, just want to check it).

  4. aaronovz1 commented on Apr 29, 2019

    @aaronovz1

    @serge1peshcoff actually the timestamps are camelCase too. Looks like we have the exact same problem. I am running the Sequelize 5.7.6.

  5. serge1peshcoff commented on Apr 29, 2019

    @serge1peshcoff
    Author

    @aaronovz1 then we are on the same page and I'm not only one facing this :D

    Btw, 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) 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"
        }
    }]
  6. aaronovz1 commented on Apr 29, 2019

    @aaronovz1

    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.

  7. serge1peshcoff commented on Apr 30, 2019

    @serge1peshcoff
    Author

    @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)

  8. aaronovz1 commented on Apr 30, 2019

    @aaronovz1

    Unfortunately I don't have the time or means to get other dialects setup at the moment.

  9. gdanov commented on May 6, 2019

    @gdanov

    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';

  10. Strate commented on May 15, 2019

    @Strate

    Almost same issue here: I use underscored: true & timestamps: true, and I expect created_at, updated_at fields in snake_case, as it was on sequelize@4. But after upgrading to sequelize@5 fields becomes createdAt and updatedAt

  11. serge1peshcoff commented on May 19, 2019

    @serge1peshcoff
    Author

    @Strate same issue as I'm facing then, it affects timestamps as well as foreign key fields. My timestamps are also in camelCase

  12. serge1peshcoff commented on May 28, 2019

    @serge1peshcoff
    Author

    I've recently understood why it's failing.
    Each model has an attributes object, where the keys are the camelCase attributes names, and each of these objects has a field field which is a snake_case or camelCase (depending on if underscored is true or false).

    Here is where the field field is set based on underscored option:

    definition.field = Utils.underscoredIf(name, this.underscored);

    In the findAll() method where the options object for SQL query is constructed, it uses Object.keys(this.rawAttributes) which will take the names in camelCase disregarding the underscored option, here:

    options.attributes = Object.keys(this.rawAttributes);

    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 to snake_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!

  13. Strate commented on Jun 19, 2019

    @Strate

    @serge1peshcoff hi, would make a PR to sequelize?

  14. serge1peshcoff commented on Jun 19, 2019

    @serge1peshcoff
    Author

    @Strate I still haven't figure out how to do it properly, do you know how?

  15. 29 remaining items

  16. liuyib commented on Mar 14, 2021

    @liuyib

    I've just upgraded from version 4 to 5.21.5. It looks like underscored: true no longer honors foreign key conventions. For example, I had to explicitly add foreignKey to make this work the way it used to:

    Feature.belongsToMany(models.permission, {
    	through: models.feature_permission,
    	foreignKey: "feature_id"
    });
    

    If I don't call it out it becomes featureId.

    Great, what you said is the root cause (underscored: true no longer honors foreign key conventions). You helped me, thanks. But, can anyone solve this problem?

  17. feeh27 commented on Mar 19, 2021

    @feeh27

    Thanks @dzvid your configuration worked for me:

    image

  18. miladmeidanshahi commented on Jun 21, 2021

    @miladmeidanshahi

    https://sequelize.org/master/manual/naming-strategies.html

    Note that in both cases the fields are still camelCase in the JavaScript side; this option only changes how these fields are mapped to the database itself. The field option of every attribute is set to their snake_case version, but the attribute itself remains camelCase.

  19. hwookim commented on Aug 12, 2021

    @hwookim

    Sadly, they don't think it's a bug...
    I'd probably just use createdAt: created_at
    I'm on ^6.6.2

  20. vkbishu commented on Sep 8, 2021

    @vkbishu

    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.

  21. imaccallum commented on Nov 10, 2021

    @imaccallum

    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 foreignKey and otherKey. Presumably if these are not specified it defaults to the camel case version and adds it to the join table or something weird like that

  22. liorsion commented on Jan 14, 2022

    @liorsion

    This issue presents an even bigger problem when using TypeScript - we can't tell the compiler which field name is used because it changes..

  23. self-assigned this
    on Jan 14, 2022
  24. ephys commented on Jan 14, 2022

    @ephys
    Member

    Maintainer here 👋. I'm trying to understand this issue a bit better. Is the issue:

    1. That you want to use created_at, user_id on the JS side, but sequelize generates camelCase,
    2. or that you want to use createdAt, userId on the JS side, but have created_at, user_id on the database side.
  25. miladmeidanshahi commented on Jan 15, 2022

    @miladmeidanshahi

    Hi @ephys absolutely number 1 :)

  26. ephys commented on Jan 15, 2022

    @ephys
    Member

    @miladmeidanshahi Thanks!

    For clarity's sake, in the following text when I say:

    • attribute, I mean the JavaScript name,
    • column, I mean the Database name.

    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 underscored option 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:

    UserModel.init({ /* attributes */ }, {
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      deletedAt: 'deleted_at',
    })

    Or configure them for every model by configuring the Sequelize instance itself:

    new Sequelize({
      define: {
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      }
    });

    For foreign keys, it's trickier. There is a way to configure it per-model but there is no system wide configuration option.

    UserModel.hasMany(Film, {
      as: 'author',
      foreignKey: {
        name: 'author_id', // the JavaScript attribute name
        field: 'author_id', // the column name
      },
    })

    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:

  27. hmarat commented on Feb 3, 2022

    @hmarat

    @ephys Thanks, worked as expected :))

  28. yisibl commented on Dec 28, 2022

    @yisibl

    @ephys After I override them globally, .update() will not work.

    new Sequelize({
      define: {
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      }
    });
    
    // Model
    Foo.prototype.change = async function() {
        const id = this.id
        return await this.update({
          updated_at: new Date(),
        }, {
          where: {
            id: id,
          },
        })
      }

    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.

  29. yisibl commented on Dec 28, 2022

    @yisibl
  30. ephys commented on Dec 28, 2022

    @ephys
    Member

    Please open a separate bug report with a reproducible example as that is not related to this thread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions