我的表用户具有以下字段
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/