问题
This is my express.js code to upload and download files to GridFS:
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 read and write from, but I'm not sure how to do that. I've seen examples online calling a GridFS constructor, but as you can see I'm not doing that here. The documentation also says that it's possible to supply a different bucket name, but I don't see anything on how.
How can I select which bucket that my files are saved to and read from?
回答1:
This is not well documented in gridfs-stream or the underlying native mongodb driver it uses, but here is how you do it:
Here is the options
object from the gridfs-stream createWriteStream
example (note the root
option):
{
_id: '50e03d29edfdc00d34000001',
filename: 'my_file.txt',
mode: 'w',
chunkSize: 1024,
content_type: 'plain/text',
root: 'my_collection', // Bucket will be 'my_collection' instead of 'fs'
metadata: {
...
}
}
Why it works:
gridfs-stream passes through the options
object you pass a call to createWriteStream
or createReadStream
to the underlying mongodb driver to create a gridStore
object to represent the file. The mongodb driver in turn recognizes root in the options object as an override of the default "fs" grid bucket prefix string.
来源:https://stackoverflow.com/questions/17113906/how-can-i-specify-a-gridfs-bucket