【发布时间】: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