Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not found error when using GridFSBucket openDownloadStream

I am able to upload a file using openDownloadStream of GridFSBucket and see that the file is uploaded and visible under songs.files chunks. But for some reason, get the following error while trying to download it -

Caught exception: Error: FileNotFound: file def1.txt was not found

My code is -

var express = require('express');
var gridModule = express.Router();
var mongoose = require('mongoose');
var fs = require('fs');

gridModule.post('/', (req, res) => {
    console.log("::::grid");
    //const gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db);

    //const writeStream = gridfs.openUploadStream('test.dat');

    var gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });

    fs.createReadStream('./def.txt').
        pipe(gridfs.openUploadStream('def1.txt')).
        on('error', function (error) {
            assert.ifError(error);
        }).
        on('finish', function () {
            console.log('done!');
            process.exit(0);
        });

});

gridModule.get('/', (req, res) => {
    var gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });
    /* var bucket = new mongodb.GridFSBucket(db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
      }); */

      gridfs.openDownloadStream('def1.txt').
        pipe(fs.createWriteStream('./def1.txt')).
        on('error', function(error) {
            console.log(":::error");
          assert.ifError(error);
        }).
        on('finish', function() {
          console.log('done!');
          process.exit(0);
        });
});

module.exports = gridModule;

I tried using ObjectId id as well but same error. Anyone any guesses what I may be doing wrong here?

Note - Code may not seem optimized here like declaring bucket twice, kindly ignore it for now as I will correct it once it works.

like image 921
eduPeeth Avatar asked Oct 17 '25 18:10

eduPeeth


1 Answers

According to the API doc here, in order to use filename as argument you should use

openDownloadStreamByName(filename, options)

not openDownloadStream. openDownloadStream takes id of the file.

like image 69
Aritra Chakraborty Avatar answered Oct 19 '25 06:10

Aritra Chakraborty