question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using underscored: true still returns attributes in camelCase

See original GitHub issue

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: https://github.com/sequelize/sequelize/issues/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
├─┬ sequelize@4.43.2
├─┬ sequelize-cli@4.1.1

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)

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:33
  • Comments:56 (4 by maintainers)

github_iconTop GitHub Comments

104reactions
dzvidcommented, Sep 24, 2019

Hello, I was having the same problem as @twistedrc1017 with the timestamps created_ at and updated_at.
The timestamps fields were both defined as snake case in the model:

image

And both undescored and undesrcoredAll were set to true in my database configuration file:

image

But I was still getting cameCase timestamps in my responses:

image

image

To get my timestamps to snake case I set the following values to createdAt:‘created_at’ and the updatedAt:‘updated_at’ in my database config (as said in the docs If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually ):

image

Then I got my timestamps in snake case:

image

image

All other fields were already being converted from camelCase to snake case and coming back in response as snake case. The only fields that were coming in response as camelCase were the two timestamps mentioned, the configuration helped solve my issue, I hope it helps you too! 😬

22reactions
max107commented, Nov 25, 2020

My grandchildren have already gone to school. But this error has still not fixed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sequelize use camel case in JS but underscores in table names
Should underscored: true and underscoredAll: true options automatically convert camelCased model's attributes names to underscored while ...
Read more >
Naming Strategies - Sequelize
The underscored option​. Sequelize provides the underscored option for a model. When true , this option will set the field option on all...
Read more >
CamelCase vs underscores: Scientific showdown - whatheco.de
Camel casing has a larger probability of correctness than underscores. · On average, camel case took 0.42 seconds longer, which is 13.5% longer....
Read more >
Camel Case vs. Snake Case vs. Pascal Case - Khalil Stemmler
Snake case (also referred to as underscore case) is when all the letters of the word are lower case but delimited by an...
Read more >
Camel case property names - Json.NET
This sample uses a T:Newtonsoft.Json.Serialization.CamelCaseNamingStrategy specified using a contract resolver to camel case serialized property names.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found