0

I've table users with following field

id,name(varchar) ,gallery(json)

gallery contains the the image path of user uploaded rows, a user can more images to his gallery and the image path of each image is stored in gallery as json

here is a sample row

id name gallery

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

Here is my code

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){
});
}

But the problem with JSON.parse(oldGallery).push(imagePath); it didn't worked console.log(JSON.parse(oldGallery).push(imagePath)) outputs 2 instead of the array.

1 Answer 1

1

Array.prototype.push() returns length of the array after pushing (not the array itself). You can concatenate it to new array instead:

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

Furthermore, the type of updatedGallery in your if clause is a String and in the else clause it will be an Array. You should make it consistent and use either strings or arrays.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah it close to answer it outputs [ 'gallery-image-1494059004453.jpeg', 'gallery-image-1494061668890.jpeg' ] but i want replace the single quotes with double
@Jabaa quotes in javascript objects are irrelevant. If it matters to you, convert it to string: JSON.stringify(JSON.parse(oldGallery).concat([imagePath]))
Now i will get the string as but i got error in mysql query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.