MongoDB GridFS, downloading image always returning only last image from a set of images

454 Views Asked by At

I am trying to retreive a set of images stored in mongoDB using mongoose and GridFS. I'm storing the filenames in an array and looping to retreive each one and store it in a local path. However, only the last image is downloaded and stored, the loop executes correctly but only the last filename is executed in each iteration.

Here filename inside gfs.exist() is always sony4 and that gets executed on each iteration and only that gets downloaded.

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express()
const mongoose = require('mongoose')
var gridfs = require('gridfs-stream');
var fs = require('fs');
mongoose.Promise = Promise
gridfs.mongo = mongoose.mongo;

mongoose.connect('mongodb://localhost:27017/CompanyDetails', { useNewUrlParser: true })
    .then(() => console.log("mongoose is up"))

let connection = mongoose.connection;

connection.on('error', function (err) {
    console.log(err);
})

app.use(cors())
app.use(bodyParser.json())

connection.once('open', () => {

    var gfs = gridfs(connection.db);
    app.get('/api/download', async (req, res) => {


        var filenames = ['asus1.jpg', 'asus2.jpg', 'asus3.jpg', 'asus4.jpg',
            'dell1.jpg', 'dell2.jpeg', 'dell3.jpg', 'dell4.png',
            'hp1.jpg', 'hp2.jpg', 'hp3.jpg', 'hp4.jpg',
            'lenovo1.jpg', 'lenovo2.jpg', 'lenovo3.jpg', 'lenovo4.jpg',
            'sony1.jpg', 'sony2.jpg', 'sony3.jpg', 'sony4.jpg'];

        for (var i = 0; i < filenames.length; i++) {
            var filename = filenames[i];
            console.log(filenames[i]);

            // Check file exist on MongoDB
            gfs.exist({ filename: filename }, (err, file) => {
                if (err || !file) {
                    res.status(404).send('File Not Found');
                    return
                }

                var readstream = gfs.createReadStream({ filename: filename });
                var fs_write_stream = fs.createWriteStream('D:/data/db/images/' + filename);
                readstream.pipe(fs_write_stream);
            });
        }
    });
})

app.listen(1234, () => console.log("Server listening at 1234"))
0

There are 0 best solutions below