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

Posted

技术标签:

【中文标题】转换为 json 时续集下划线/蛇形大小写【英文标题】:Sequelize underscore / snake case when converted to json 【发布时间】:2016-02-24 03:32:05 【问题描述】:

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

目前;

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"

有什么想法吗?

【问题讨论】:

您使用的是什么版本的续集?查看此***.com/questions/18858337/… 【参考方案1】:

不可能。属性名称用于获取值,toJSON 使用获取值的方法。覆盖 toJSON 或不使用骆驼 大小写的属性名称。

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

【讨论】:

以上是关于转换为 json 时续集下划线/蛇形大小写的主要内容,如果未能解决你的问题,请参考以下文章