aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

How do you set the bucket to write to and read from? #24

Closed pateras closed 11 years ago

pateras commented 11 years ago

This is how I'm uploading and downloading files using gridfs-stream:

var fs = require("fs"); var gridStream = require("gridfs-stream"); var mongoose = require("mongoose");

exports.init = function(app, db) { var grid = gridStream(db, mongoose.mongo);

app.post("/UploadFile", function(request, response)
{
    var file = request.files.UploadedFile;

    var meta = request.param("Meta");
    var name = request.param("Name");

    var stream = grid.createWriteStream(
    {
        filename: name,
        metadata: meta
    });

    fs.createReadStream(file.path)
    .on("end", function()
    {
        response.send({ Success: true });
    })
    .on("Error", function(error)
    {
        HandleError(error, response);
    })
    .pipe(stream);
});

app.get("/DownloadFile", function(request, response)
{
    var selector = request.param("Selector");

    response.writeHead(200, { "Content-Type" : "image/png"});
    grid.createReadStream({ filename: "FileUploadNamed" }).pipe(response);
});

}

It works perfectly, but I'd like to specify a bucket to write to and read from. How can I do that?

Thanks for this great package!

Reggino commented 11 years ago

What do you mean by "bucket": a database or a collection? (i know the term bucket in Amazon S3, that could be compared to database)

A different database can be used by passing another db to your grid-constructor A different collection can be used by passing in a root-configuration to both your createReadStream and createWriteStream

Does this answer your question?

pateras commented 11 years ago

GridFS uses the term bucket to refer to the files and chunks. So fs.files and fs.chunks are both collections, but they make up a single "fs" bucket, as I understand it. See here: http://docs.mongodb.org/manual/core/gridfs/#gridfs-collections

Anyway, setting the root option was indeed what I needed to do. Thank you.

cyrilchapon commented 5 years ago

What do you mean "The root option".

Closing this ticket with a documented solution would have been a great idea.

tjesposito commented 4 years ago

In case anyone stumbles across this, found it in the type definitions, literally the option called 'root', this worked fine for me:

gfs.createWriteStream({
   filename: file.originalName,
   content_type: file.mimetype,
   mode: 'w',
   root: 'customBucket', /* customBucket.files, customBucket.chunks */
   metadata: {...}
})