Mik*_*koP 9 mysql json node.js sequelize.js
我已经将模型定义为
module.exports = function (sequelize, DataTypes) {
const MyModel = sequelize.define('MyModel', {
data: {
type: DataTypes.JSON,
...
},
...
});
return MyModel;
};
Run Code Online (Sandbox Code Playgroud)
我用它来查询它
MyModel.findAll().then(myModels => ...);
Run Code Online (Sandbox Code Playgroud)
但是,data查询结果中的字段是字符串,而不是JSON对象.我如何解决它?
Jal*_*lal 14
它还不支持MySQL JSON数据类型#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;
};
Run Code Online (Sandbox Code Playgroud)
我还在github sequelize-json上找到了这个软件包你可以尝试一下,如果你不想使用getter和setter.
小智 13
无需使用 getter 和 setter,因为 sequelize 现在支持 JSON。请参阅sequelize api
Jalal 的回答很好,但对我不起作用,除非我稍微调整一下。以下是对我有用的内容:
首先:创建一个迁移,将您想要的字段添加为 type TEXT。示例 - 我想向表中添加一个名为address的Stores字段:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addColumn("Stores", "address", Sequelize.TEXT);
},
down: (queryInterface, Sequelize) => {
return queryInterface.removeColumn("Stores", "address");
}
};
Run Code Online (Sandbox Code Playgroud)
下一步: 在您的模型中,将带有 getter 和 setter 的字段添加到您的字段和数据类型列表(对象)中:
address: {
type: DataTypes.TEXT,
get: function() {
return JSON.parse(this.getDataValue("address"));
},
set: function(value) {
return this.setDataValue("address", JSON.stringify(value));
}
},
Run Code Online (Sandbox Code Playgroud)
所以我的整个模型看起来像这样:
module.exports = (sequelize, DataTypes) => {
const Store = sequelize.define(
"Store",
{
name: DataTypes.STRING,
isActive: DataTypes.BOOLEAN,
address: {
type: DataTypes.TEXT,
get: function() {
return JSON.parse(this.getDataValue("address"));
},
set: function(value) {
return this.setDataValue("address", JSON.stringify(value));
}
}
},
{}
);
Store.associate = function(models) {
// associations can be defined here
Store.hasMany(models.Order, {
foreignKey: "id",
targetKey: "storeId"
});
};
return Store;
};
Run Code Online (Sandbox Code Playgroud)
现在,您可以像在 db 中使用 JSON 类型字段一样创建和检索记录。
例如: const store = await Store.create({name: "Joe's corner store", address: {address1: "123 test street", city: "Los Angeles", state: "CA"}})
一些注意事项:
在上面的代码块中...
address为您要使用的字段名称。Stores为您的模型/表名称。return了设置器,否则在尝试创建新记录时出错(Jalal 拥有它的方式)。小智 2
MySQL 不支持 JSON 数据类型。
请参阅此处的文档http://docs.sequelizejs.com/en/v3/docs/models-definition/#data-types
解决方法可能是在查询时使用文本和字符串化/解析
| 归档时间: |
|
| 查看次数: |
14701 次 |
| 最近记录: |