javascript - 在node js中将json插入到mysql表中

标签 javascript mysql json node.js express

我的表用户具有以下字段

id,名称(varchar),画廊(json)

gallery 包含用户上传行的图像路径,用户可以将更多图像添加到他的图库中,并且每个图像的图像路径以 json< 的形式存储在 gallery 中/p>

这是一个示例行

id name gallery

1  blob ["test.jpg","test1.jpeg"]

这是我的代码

function(req,res){
//image path after upload
var imagePath =uploadS3();

//SELECT gallery FROM user   and store to oldGallery
 var oldGallery = getCurrentGallery()
 var updatedGallery;
if(oldGallery==null){
    updatedGallery = "[\""+imagePath+"\"]"

}else{
    //concatinate the gallery row with new imagepath
      updatedGallery = JSON.parse(oldGallery).push(imagePath);
 }

   db.query("UPDATE users SET gallery=? ",[updatedGallery],function(error,result){
});
}

但是 JSON.parse(oldGallery).push(imagePath); 的问题没有起作用 console.log(JSON.parse(oldGallery).push(imagePath)) 输出 2 而不是数组。

最佳答案

Array.prototype.push()返回压入后数组的长度(不是数组本身)。您可以将其连接到新数组:

updatedGallery = JSON.parse(oldGallery).concat([imagePath]);

此外,if 子句中 updatedGallery 的类型是 String,而在 else 子句中它是将是一个数组。您应该使其保持一致并使用字符串或数组。

关于javascript - 在node js中将json插入到mysql表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818556/

相关文章:

mysql - 仅在使用 WHERE...IN 和嵌入式 SELECT 时获取第一行

Javascript > 显示回答是什么

javascript - 强制小数点后两位数的正则表达式

php - 索引.php :13 Uncaught SyntaxError: Unexpected token: error message in Ci

javascript - 显示来自函数的数据

java - Gson解析集合

python - 在列表理解中将字符串添加到字典

c# - 用于验证 URL 或域名的正则表达式。

javascript - 新的数组语法,多个参数

mysql - System.DateTime 类型不是受支持的类型。更改为使用 System.DateTimeOffset