dev dev
dev dev

Reputation: 123

save images mongodb node js

schema

 images:{ type : Array , "default" : [] }

controller

   return new Promise(function(resolve,reject){
        var dt = new Date(req.body.dateOfBirth)
            var experiences = new Experiences({
            'images': req.body.images

        });
        experiences.save(function(err,experiences){
            if(err){
                reject(err);
            }else{
                resolve(experiences);
            }
        });
    });

I need to save more than one image into single image

posting Data as :

"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb","https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb"

but when i viewing my document. getting result like this :

"images" : [ 
    "\"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb\",\"https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb\""
]

what am i doing wrong please help? i want result like:

"images" : [ 
"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb","https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb"
]

Upvotes: 0

Views: 202

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26360

My guess is that req.body.images is stringified. I believe it is a string containing many values, not an array. When you post that to MongoDB, since you specified that images must be an array, it saves it as an array of strigified values.

So, blind guess, but I believe you are posting (client-side) something like :

$.post("/save", { images : JSON.stringify(imagesArray) } )

when you should just post your array as is :

$.post("/save", { images : imagesArray} )

But it's hard to know for sure, because we don't have the front-end code or even console.log(req.body.images)

Upvotes: 1

Related Questions