2017-05-06 76 views
0

我有表的用户与以下领域插入JSON到MySQL表中节点JS

ID,名称(VARCHAR),画廊(JSON)

gallery包含用户上载的行的图像路径,用户可以更图像以他的画廊和各图像的图像路径存储在gallery为JSON

这里是一个示例行

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而不是阵列的问题。

回答

1

Array.prototype.push()返回推后数组的长度(不是阵列本身)。你可以把它串联到新的数组来代替:

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

此外,updatedGalleryif条款类型为Stringelse子句中这将是一个Array。您应该使其一致并使用字符串或数组。

+0

是啊,回答接近它输出'[“画廊,图像1494059004453.jpeg”, “画廊,图像1494061668890.jpeg”]',但我想用javascript对象双 – Jabaa

+0

@Jabaa引号替换单引号是无关紧要的。如果它对你很重要,将其转换为字符串:'JSON.stringify(JSON.parse(oldGallery).concat([imagePath]))' – madox2

+0

现在我将得到字符串,但我在mysql查询中出错 – Jabaa