Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize underscore / snake case when converted to json

Using Node and Sequelize, is it possible to define a model which uses camelCase for the attributes, but underscore/snake case when converted to json?

Currently;

var User = seq.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    shortLivedToken: {
        type: Sequelize.STRING,
        field: 'short_lived_token'
    },
    longLivedToken: {
        type: Sequelize.STRING,
        field: 'long_lived_token'
    }
}, {
    underscored: true,
    underscoredAll: true,
});

Turns into when calling response.json(user)

{
  "id": null,
  "shortLivedToken": "abcde",
  "longLivedToken": "fghji",
  "updated_at": "2015-11-21T18:32:20.181Z",
  "created_at": "2015-11-21T18:32:20.181Z"
}

And I want it to be

{
  "id": null,
  "short_lived_token": "abcde",
  "long_lived_token": "fghij",
  "updated_at": "2015-11-21T18:32:20.181Z",
  "created_at": "2015-11-21T18:32:20.181Z"
}

Any ideas?

like image 725
Poyan Avatar asked Jul 18 '26 12:07

Poyan


1 Answers

Not possible. The attribute names are used for getting values, toJSON uses methods for getting values. Overwrite toJSON or don't use camel cased attribute names.

https://github.com/sequelize/sequelize/issues/4906

like image 183
Poyan Avatar answered Jul 20 '26 02:07

Poyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!