How can I specify a GridFS bucket?

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!