A.G.Progm.Enthusiast
A.G.Progm.Enthusiast

Reputation: 1010

How to display multiple images from MongoDB in browser using node js

I have multiple photos (images) stored in my MongoDB database which has following schema :

schema = new Schema( {
   name : String,
   photo : {data:Buffer, contentType: String}
});

Now, let us assume that I have hundred photos stored in the database by above schema with each photo stored as a document.

I want to view all these stored pictures in browser by firing a post API with each page showing 10 photos. There should be a 'prev' or 'next' button which will help me go to the previous or next page respectively.

I have tried following code, which is always showing the last photo coming in the result set when the forEach loop iteration ends.

app.post('/show', function(req, res) {
   var ph;
   //model is a mongodb model object for the schema
   model.find({}, function(err, result) {
   result.forEach(function(pic) {
   ph = pic['photo']['data'];
   })

  res.writeHead(200, {'Content-Type': 'image/jpeg' } );
  res.end(ph, 'binary');
});
}

Any help on how can I write the html to dynamically show the fetched pictures from database on the browser would be great help.

Thanks.

Upvotes: 0

Views: 1325

Answers (2)

VirgilCane
VirgilCane

Reputation: 49

You could push an array containing all entries in your db to your HTML like so:

var ph;

app.get('/show',(req,res)=>{


model.find({}, async (err,cb)=>{ 
    if(!err){
        ph = await cb;

    }else{
        throw err;
    }

res.render('your_ejs_file_here.ejs',{ph: ph});

});

Upvotes: 0

njLT
njLT

Reputation: 474

Instead of forEach use map

ph = result.map(pic => pic['photo']['data']);

This will give you the 100 photos in the ph array. You might want to just get 10 photos at a time, in which case take a look at this

Upvotes: 1

Related Questions