随笔

Sequelize-ORM

sequelizenodeorm框架,支持pg, mysql, sqlite3, mssql

常用操作

findOne({ where: { xxx:xxx } })
findAll({ where: { xxx:xxx } })
update({ xxx:xxx }, { where: { xxx:xxx } })
destroy({ where: { xxx:xxx } })
create({ xxx:xxx })

操作结果

  • 查询返回对象,null或数组
  • 创建会返回创建的对象
  • 更新返回一个数组,第一个元素代表删除的数量([2],更新了两个)
  • 删除返回数量

错误捕获

错误定义:http://docs.sequelizejs.com/class/lib/errors/index.js~BaseError.html
可以按照定义里面的给出对应中文提示到前台,当然,也可以不提示,毕竟看产品面向的是B端还是C端, 重要的是能在不泄露信息的情况下定位问题。以下为一个唯一键校验错误

{
    "name":"SequelizeUniqueConstraintError",
    "errors":[
        {
            "message":"PRIMARY must be unique",
            "type":"unique violation",
            "path":"PRIMARY",
            "value":"20",
            "origin":"DB",
            "instance":{
                "id":20,
                "updatedAt":"2018-12-01T15:38:27.297Z",
                "createdAt":"2018-12-01T15:38:27.297Z"
            },
            "validatorKey":"not_unique",
            "validatorName":null,
            "validatorArgs":[

            ]
        }
    ],
    "fields":{
        "PRIMARY":"20"
    },
    "parent":{
        "code":"ER_DUP_ENTRY",
        "errno":1062,
        "sqlState":"23000",
        "sqlMessage":"Duplicate entry '20' for key 'PRIMARY'",
        "sql":"INSERT INTO `apps` (`id`,`createdAt`,`updatedAt`) VALUES (20,'2018-12-01 15:38:27','2018-12-01 15:38:27');"
    },
    "original":{
        "code":"ER_DUP_ENTRY",
        "errno":1062,
        "sqlState":"23000",
        "sqlMessage":"Duplicate entry '20' for key 'PRIMARY'",
        "sql":"INSERT INTO `apps` (`id`,`createdAt`,`updatedAt`) VALUES (20,'2018-12-01 15:38:27','2018-12-01 15:38:27');"
    },
    "sql":"INSERT INTO `apps` (`id`,`createdAt`,`updatedAt`) VALUES (20,'2018-12-01 15:38:27','2018-12-01 15:38:27');"
}

文档地址:http://docs.sequelizejs.com/manual/installation/getting-started.html

本文链接:https://note.lilonghe.net/post/sequelize-orm.html

-- EOF --