序列化 JSON 数据类型
我已将模型定义为
module.exports = function (sequelize, DataTypes) {
const MyModel = sequelize.define('MyModel', {
data: {
type: DataTypes.JSON,
...
},
...
});
return MyModel;
};
我使用查询它
MyModel.findAll().then(myModels => ...);
但是,查询结果中的 data
字段是一个字符串,而不是 JSON 对象.我该如何解决?
However, data
field in the query result is a string, not a JSON object. How do I fix it?
推荐答案
还不支持 MySQL JSON数据类型#4727.但你可以这样做:
It's not supported yet MySQL JSON Data Type #4727. But you can do something like this:
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如果你可以试试不想使用 getter 和 setter.
I also found this package on github sequelize-json you can give it a try if you don't want to use getters and setters.
相关文章