Search code examples
imagemongodbexpressuploadgridfs-stream

Very new to express and mongodb with gridfs-stream


and thanks in advance for any help you guys can give me. I am trying to use mongodb, mongoose, gridfs-strea, and express to store img files on mongodb. I do not want to store the file in a folder. I want gfs.createWriteStream to take the file directly from app.post from express. App.post is currently saving some strings through a schema model into mongodb. The form that routes to app.post contains strings and a input for img file.

I tried to do this(dnimgfront being the name of the input):

dnimgfront:req.pipe(gfs.createWriteStream('req.body.dnimgfront'))

I am getting back.

TypeError: Object function Grid(db, mongo) {
 if (!(this instanceof Grid)) {
   return new Grid(db, mongo);
 }

 mongo || (mongo = Grid.mongo ? Grid.mongo : undefined);

My problem is I have to be able to store the img and the strings from the same app.post save function. Any ideas?

What I'm using to connect to mongodb is:

mongoose.connect('mongodb://localhost/veeltaxi');

var con=mongoose.connection;

con.once('open', function(){
    console.log('connected to mongodb succesfully!')
});

Thanks in advance for your help.


Solution

  • First, you need an instead of gridfs-stream:

    var GridStream = require('gridfs-stream');
    var mongodb = require('mongodb');
    var gfs = new GridStream(mongoose.connection,mongodb);
    

    At which point you can create the write stream and pipe:

    var writeStream = gfs.createWriteStream({
       filename: filename, // the name of the file
       content_type: mimetype, // somehow get mimetype from request,
       mode: 'w' // ovewrite
    });
    
    req.pipe(writeStream);
    

    However, at this time the Node.js MongoDB Driver is at version 2.0 which uses Streams 2, so there is no reason to use gridfs-stream if you're using that version of the mongodb lib. See the source code for v2.0.13. FYI, the stream that is implemented in the updated driver is Duplex. (Aside: gridfs-stream has its share of problems, and while actively maintained, is not very frequent.)