eduPeeth
eduPeeth

Reputation: 1868

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.

Upvotes: 4

Views: 6610

Answers (3)

Jeff R
Jeff R

Reputation: 645

Another possible explanation for this, if you're already calling openDownloadStream and still experiencing the FileNotFound error, and you are 100% the id is correct, is that you didn't pass a MongoDB ObjectId type.

In my case, I was passing an id string instead of an id as an ObjectId.

bucket.openDownloadStream(new mongoose.Types.ObjectId(id));

vs

bucket.openDownloadStream(id);

Upvotes: 4

Tim5chneider
Tim5chneider

Reputation: 1

The following code works for me:

const { ObjectId } = require('mongodb');

bucket.openDownloadStream(new ObjectId(id));

Upvotes: 0

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

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.

Upvotes: 6

Related Questions