// 路由
router.get("/winner", async function (req, res, next) {
let id = Number(req.query.id);
let fileUrlId = req.query.fileUrlId;
if (!id && !fileUrlId) {
return res.send(failModel(2004, false, null));
}
const resGetWC = await getCurrentFileUrl(id);
if (resGetWC.length === 1) {
const tempFileUrl = JSON.parse(resGetWC[0].fileUrl).reduce(
(result, item) => {
if (item.id === fileUrlId) {
item.winnerCount
? (item.winnerCount = item.winnerCount + 1)
: (item.winnerCount = 1);
}
result.push(item);
return result;
},
[]
);
const resultUpdate = await updateWinner(
id,
JSON.stringify(tempFileUrl)
);
if (resultUpdate?.affectedRows === 1) {
return res.send(successModel());
}
return res.send(failModel(-1, false, null));
}
return res.send(failModel(-1, false, null));
});
// updateWinner
const updateWinner = async (id, fileUrl) => {
const resultGet = await getCurrentWinnerCount(id);
if (resultGet.length === 1) {
const sql = `
UPDATE vs_make_lists
SET fileUrl = ${escapeSqlString(fileUrl)}, winnerCount ='${
resultGet[0].winnerCount ? resultGet[0].winnerCount + 1 : 1
}'
WHERE list_id = ${id}
`;
return execSQL(sql);
}
return;
};
const escapeSqlString = str => {
return mysql.escape(str);
};
问题:
本地数据库是没有复现出来的,线上的时候会出现此问题
从你的描述,本地数据库可以正常工作,线上数据库在更新 JSON 字段的时候出现问题,原因主要有两点:
UPDATE vs_make_lists SET fileUrl = ${escapeSqlString(JSON.stringify(tempFileUrl))}
const sql = UPDATE vs_make_lists SET fileUrl = ${escapeSqlString(JSON.stringify(tempFileUrl))}
execSQL(sql);
这段代码对我很有帮助,我会按照你的建议修改我的代码,转义JSON字符串后再更新到数据库。
非常感谢你的反馈和提出的建议解决方案。这对我理解问题和提高编码意识很有帮助。
我会将你的解答和建议记录下来,以后遇到类似的问题可以参考。
再次感谢!
你提到的两点,一是检查数据库支持度,二是字符串转义,这两个点在操作数据库时非常重要,容易出现问题。记录并理解这两个点,对你以后处理数据库非常有好处。
直接使用MYSQL自带的JSON函数处理