Sequelize JSON数据types
我已经定义了一个模型
module.exports = function (sequelize, DataTypes) { const MyModel = sequelize.define('MyModel', { data: { type: DataTypes.JSON, ... }, ... }); return MyModel; };
我使用查询
MyModel.findAll().then(myModels => ...);
但是,查询结果中的data
字段是一个string,而不是JSON对象。 我如何解决它?
目前还不支持MySQL JSON数据types#4727 。 但是你可以做这样的事情:
module.exports = function (sequelize, DataTypes) { const MyModel = sequelize.define('MyModel', { data: { type: Sequelize.TEXT, get: function () { return JSON.parse(this.getDataValue('value')); }, set: function (value) { this.setDataValue('value', JSON.stringify(value)); }, , ... }, ... }); return MyModel; };
我也在github sequelize-json上find了这个包,如果你不想使用getter和setter,那么你可以尝试一下。
JSON数据types不支持MySQL。
请参阅文档http://docs.sequelizejs.com/en/v3/docs/models-definition/#data-types
解决方法是在查询时使用文本和string化/parsing
- NodeJS HTTP请求不按顺序执行
- 意外的令牌与有效的JSON?
- parsing从Netsuite到Heroku的JSON HTTP请求会返回错误“SyntaxError:Unexpected token p”
- 使用JSONPath和JSONStreamparsingjsonstream
- Express / Node.js:包含外部API查询结果; 加上故障排除路线
- 节点/玉 – 显示JSON项目而不知道键
- 不确定Node.js代码是否是asynchronous的
- 使用Google Maps API从Zip代码中获取城市,然后将其写入JSON?
- Nodejs,如何获取嵌套的json对象的值,中间键是未知的