转换为 json 时续写下划线/蛇形大小写

Sequelize underscore / snake case when converted to json

使用 Node 和 Sequelize,是否可以定义一个模型,该模型使用 camelCase 作为属性,但在转换为 json 时使用 underscore/snake 大小写?

目前;

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,
});

调用时变为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"
}

我希望它是

{
  "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"
}

有什么想法吗?

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

编辑:

使用 underscored 选项。

sequelize-cli model:generate --name User --attributes login:string --underscored

source code


Hacky,但它对你有用。

import { promises as fsPromises } from 'fs';

const files = await fsPromises.readdir(path.join(/* path to directory */));

const file =
    files.filter((allFilesPaths) =>
        new RegExp(/* name of file */).test(allFilesPaths),
    )?.[0] ?? null;

if (!file) throw new Error(`file not found`);

const fileContents = await fsPromises
    .readFile(path.join(/* path to file */), 'utf-8')
    .replace('updatedAt', 'updated_at')
    .replace('createdAt', 'created_at');

此外,这是 7 年前发布的,所以如果我是你,我会再次深入研究他们的文档。也许他们现在允许了。