简体   繁体   English

使用 sequelize 原始查询 node.js 在结果中将 tinyint 字段转换为布尔值

[英]convert tinyint field as boolean in result using sequelize raw query node.js

I have problem that when I use a raw query in sequelize which is select query the tinyint fields returned are as integers and not as true / false .我有一个问题,当我在 sequelize 中使用原始查询时,选择查询返回的 tinyint 字段是整数而不是true / false

Here is the code:这是代码:

router.route('/').get(function (req, resp) {
    sequelize.query("select * from territory_device", {model: territoryDevice}).then(result => {
        resp.send(result)
    })
})

And here is the result I recieve:这是我收到的结果:

结果

Although I defined the field is_active as a boolean in the model it gets returned as an integer and I am using MySQL dialect .尽管我将字段is_active定义为模型中的布尔值,但它以整数形式返回,并且我使用的是 MySQL 方言。

The problem is mysql side.问题是mysql方面。 Mysql returns 0 or 1 for boolean datatype. Mysql 为布尔数据类型返回 0 或 1。 You can change the datatype or just handle 0 or 1 in your program您可以在程序中更改数据类型或仅处理 0 或 1

instead of using {raw: true} , you can get Sequelize's wrapper and convert the response using .toJSON() method on the returned response.而不是使用{raw: true} ,您可以获取 Sequelize 的包装器并在返回的响应上使用.toJSON()方法转换响应。

then you will get the tinyint parsed as boolean as long as its DataType.BOOLEAN in Sequelize's model object.那么只要它在 Sequelize 的模型对象中的 DataType.BOOLEAN ,您就会将 tinyint 解析为布尔值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM