【问题标题】:Sequelize showing error: Unexpected token u in JSON at position 0Sequelize 显示错误:位置 0 处 JSON 中的意外标记 u
【发布时间】:2022-01-16 01:05:14
【问题描述】:

我正在尝试使用 sequelize 更新 mysql 数据库中的记录,但它不起作用。

我收到了这个错误

JSON 中位置 0 处的意外标记 u

型号

module.exports = sequelize.define("branches", {
address: Sequelize.TEXT(),
company: Sequelize.STRING(),
 codeConfig: {
    type: Sequelize.STRING,
    allowNull: false,
    get: function () {
        return JSON.parse(this.getDataValue('codeConfig'));
    },
    set: function (val) {
        return this.setDataValue('codeConfig', JSON.stringify(val));
    }
},

});

更新功能

router.put('/:id', async (req, res) => {

const { address, company} = req.body;

 try {

    const branches = await Branches.findOne({ where: { code: req.params.id } });
    if (!branches) return res.json({ msg: "Branch Not Found" });

    Branches.update({ "address": "No. 10 distreet street" }, {
        where: {
            code: "WHJ5uBdriI"
        }
    }).then(function (newBranch) {
        return res.json({ msg: "Updated" });
    });


} catch (error) {
    console.error(error.message);
    res.status(500).send("Server Error");
}

});

错误输出

【问题讨论】:

  • 你能在JSON.parse之前的get函数中尝试console.log(this.getDataValue('codeConfig'))吗?我的猜测是 DB 中的这个原始值不在有效的 JSON 中。
  • @Emma 我试过了,但没有显示任何价值
  • 我明白了。这意味着 this.getDataValue('codeConfig') 在某种程度上是未定义的。试试console.log(this.toJSON())

标签: mysql node.js sequelize.js


【解决方案1】:

autoJsonMap: false, 添加到您的续集的dialectOptions

例子:

let sequelize = new Sequelize(DATABASE, USER, PASSWORD, {
    // some other options
    dialectOptions: {
        autoJsonMap: false,
    }
});

参考:

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    相关资源
    最近更新 更多