javascriptmongodbgridfsbucketgridfs-stream

How can I specify a GridFS bucket when executing find() using gridfs-stream


Using gridfs-stream, how do I specify the bucket name when finding and fetching files?

My question is a follow-up to the following question found on stackoverflow at How can I specify a GridFS bucket

The solution there provides an example of how to specify the bucket when I call createWriteStream. Based upon the code offered by @vsivsi, I am able to add files to my custom bucket using the 'root' option in the following code:

// fyi, req.file has been populated using multer
var gfs = Grid(mongoose.connection.db);
var writeStream = gfs.createWriteStream({
    filename: req.file.originalname,
    mode: 'w',
    content_type: req.file.mimetype,
    root: 'private'
});

This successfully adds my file to private.files and private.chunks. So now I want to find and read my uploaded files. My find() which does not use buckets looks like this:

var gfs = Grid(mongoose.connection.db);
gfs.find({
    filename: req.params.filename
}).toArray(function(err, files){ 
     // bunch of processing here... 
});

Now how do I tell find which bucket/root to query?

I am assuming that I will be able to use the same 'root' option when I call createReadStream(), but first I need to find it. Is there a way to tell gridfs-stream what bucket/root to use?


Solution

  • I think I found my own answer. Looking at the source for gridfs-write, I found the following prototype:

    Grid.prototype.collection = function (name) {
      this.curCol = name || this.curCol || this.mongo.GridStore.DEFAULT_ROOT_COLLECTION;
      return this._col = this.db.collection(this.curCol + ".files");
    }
    

    So I can now search my bucket using the following:

    var gfs = Grid(mongoose.connection.db);
    gfs.collection('private').find({
      filename: req.params.filename
    }).toArray(function(err, files){
        // handle err and no files...
        let readStream = gfs.createReadStream({
            filename: files[0].filename,
            root: 'private'
        });
        // ... etc. ...
    });
    

    Hope this helps someone else who might come looking for it!