sqlite 数据库中的JSON数组未更新

vs91vp4v  于 2023-08-06  发布在  SQLite
关注(0)|答案(1)|浏览(120)

我有一个文章数据库,其中一列是评论部分,以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)]不应该在我的数组中添加新元素吗?

8yoxcaq7

8yoxcaq71#

使用JSON_INSERT(),数组索引为"#",在json数组的末尾添加注解:

UPDATE articles
SET comments = JSON_INSERT(comments, '$[#]', ?)
WHERE article_id=?

字符串

相关问题