skyworker
V2EX  ›  Node.js

kaojs 架构,读取 mysql 的 json 类型字段的时候,能否自动转换成 json 类型,而不是 string 类型?

  •  
  •   skyworker · Feb 23, 2018 · 6156 views
    This topic created in 3176 days ago, the information mentioned may be changed or developed.

    目前有个系统,架构是 koa+mysql(历史原因,没有使用 mongdb),为了便于扩展,mysql 表里面用了很多类似名为 detail/tags 的 json 类型字段.

    例如有个 users 表,包含了 tags 字段,保存该用的额 tag, 例如['可爱','型男','80 后']等数据.在 koa 读取这个用户的时候:

    const user = await this.model('users').where({id: 1}).find();

    读取的结果,user.tags 是一个 string 类型的值,而不是标准的 json array. 当然手工可以转换成 json,但是如果字段多的话,就会很累.

    刚刚接触 nodejs,不知道有没有自动化的处理方法,让框架能自动识别 model 中的 json fields 类型,自动转换成 json 类型?

    Supplement 1  ·  Feb 23, 2018
    PS: 在 users 表中, tags 是一个 mysql 支持的新的 json 类型的 field, 而不是 varchar 类型或 text 类型
    8 replies  •  2018-03-03 16:15:06 +08:00
    noe132
    noe132
    Feb 23, 2018 via Android
    1
    自己写中间件转换呗。。。mysql 和 node 又不知道你的 string 是不是合法的 json string,mysql 也没有 json 这个类型
    skyworker
    skyworker
    OP
    Feb 23, 2018
    2
    @noe132 mysql 5.7 已经支持 json 类型的字段了不过不支持索引,并且提供的有 json 相关的函数, 用起来还可以.
    zenxds
    zenxds
    Feb 23, 2018
    3
    model 里面写 getter 吧
    feichao
    feichao
    Feb 26, 2018
    4
    暴力一点的方法可以 hack 一下原型链,找到 find 方法对应的构造函数,然后在原型上添加一个方法,大概就像这个样子:
    XXX.prototype.findAndConvertToArray = async function () {
    const stringValue = await this.find()
    return JSON.parse(stringValue)
    }
    feichao
    feichao
    Feb 26, 2018
    5
    在原型链上添加方法之后就可以像 find 一样调用 findAndConvertToArray 方法了。不过记得给新增的方法加上注释,防止别人不理解。
    skyworker
    skyworker
    OP
    Feb 26, 2018
    6
    @feichao 是的,目前采用的就是这种办法. 原以为 koajs 之类的框架,应该有自动 convert 的 feature,看来没有了
    vcfvct
    vcfvct
    Mar 3, 2018 via Android❤️1
    7
    可以看看 typeorm 里有没有好的方案,converter 或者 mapper 之类的。
    skyworker
    skyworker
    OP
    Mar 3, 2018
    8
    @vcfvct 多谢 我们看下, 和 Laravel 的 Doctrine 还是比较类似的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2664 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 14:42 · PVG 22:42 · LAX 06:42 · JFK 09:42
    ♥ Do have faith in what you're doing.