2017-05-06 78 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