Why Can't I set the id on GridFS using an id from a related mongo document Why Can't I set the id on GridFS using an id from a related mongo document mongoose mongoose

Why Can't I set the id on GridFS using an id from a related mongo document


I'm going to answer my own question because I found the answer when going through the source code of mongoose server.js and gridfs-stream.

You can use the ObjectId of a related document for the ObjectId of the stored file.

However, if you provide a "root" option on the upload, you'll need to use it to use it in the download code as well. Otherwise, mongoose assumes the collection is the base collection.

So this works:

exports.uploadFile = function(req, res){    var file = req.files.upload;    var docId = mongoose.Types.ObjectId(req.query.docId);    var filename = req.query.ileName;    var contentType = file.type;    if(!file) return res.send({result: 'NO_FILE_UPLOADED'});    var writestream = gfs.createWriteStream({        _id: docId,        filename: filename,        mode: 'w',        root: 'documents'    }); // more here but ommitted };exports.downloadFile = function(req, res){    var id = gfs.tryParseObjectId(req.query.docId);    //note that options now includes 'root'    var options = {_id: id, root: 'documents'};    try{        gfs.createReadStream(options).pipe(res);    } catch(err){        console.log(err);    }};


Have you tried to convert req.query.docId to ObjectId? If you are receiving value from query it will be string, so you need to convert it to ObjectId if this type of _id was used during upload.

exports.downloadFile = function(req, res){    console.log(req.query.docId);    var readstream = gfs.createReadStream({_id: mongoose.Types.ObjectId(req.query.docId)});    readstream.pipe(res);};


I looked at the gridfs-stream page, are you assigning the mongoose driver to it.

var conn = mongoose.createConnection(..);conn.once('open', function () {  var gfs = Grid(conn.db, mongoose.mongo); //missing parameter  // all set!})

or

Grid.mongo = mongoose.mongo;  //missing var conn = mongoose.createConnection(..);conn.once('open', function () {  var gfs = Grid(conn.db);  // all set!});