V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
skyworker
V2EX  ›  Node.js

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

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