我有一个文章数据库,其中一列是评论部分,以JSON格式存储为数组。当用户向文章添加评论时,在服务器中调用:
app.post("/add-comment", (req, res) => {
const id = req.body.id;
const newComment = req.body.comment;
console.log("Adding comment: (%s) to articleID: %i", newComment, id);
global.db.run(`
UPDATE articles
SET comments = JSON_SET(comments, '$[JSON_ARRAY_LENGTH(comments)]', "?")
WHERE article_id=?`,
[newComment,id],
function (err) {
if (err) {
next(err); //send the error on to the error handler
}
});
});
字符串
数据库中的JSON数组看起来像这样:
["first comment","second comment"]
型
但是,我得到了这个错误:
SQLITE_RANGE: column index out of range
--> in Statement#run([ 'asd', '3' ], [Function (anonymous)])
型$[JSON_ARRAY_LENGTH(comments)]
不应该在我的数组中添加新元素吗?
1条答案
按热度按时间8yoxcaq71#
使用
JSON_INSERT()
,数组索引为"#"
,在json数组的末尾添加注解:字符串