【问题标题】:insert json into mysql table in node js将json插入到节点js中的mysql表中
【发布时间】:2017-10-04 17:44:03
【问题描述】:

我有以下字段的表格用户

id,name(varchar) ,gallery(json)

gallery包含用户上传行的图片路径,用户可以将更多图片添加到他的图库中,每张图片的图片路径以json形式存储在gallery

这是一个示例行

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 而不是数组。

【问题讨论】:

    标签: javascript mysql json node.js express


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,它接近回答它输出[ 'gallery-image-1494059004453.jpeg', 'gallery-image-1494061668890.jpeg' ],但我想用双引号替换单引号
    • javascript 对象中的 @Jabaa 引号无关紧要。如果对您很重要,请将其转换为字符串:JSON.stringify(JSON.parse(oldGallery).concat([imagePath]))
    • 现在我将得到字符串,但我在 mysql 查询中出错
    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2020-09-23
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多