aheckmann / gridfs-stream

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

WriteStream didn't save in MongoDB #104

Closed Neewd closed 7 years ago

Neewd commented 7 years ago

Hello,

It's my first time using gridfs with mongoose and I just followed the steps from the guide. But when I upload my picture my

writestream.on('finish', function(file){
      console.log(file);
    });

is never called.

Here is my entire code.

router.post('/api/picture/profile', customMW.auth, upload.single('coverImage'), function(req, res) {

    var gridfs = app.get('gridfs');

    var writestream = gridfs.createWriteStream({
        mode : 'w',
        filename: 'myfile.txt'
    });
    var readStream = fs.createReadStream("/Users/clem/Desktop/myfile.txt");
    readStream.pipe(writestream);

    writestream.on('error', function(err){
      console.log(err);
    });

    writestream.on('finish', function(file){
      console.log(file);
    });
var Grid = require('gridfs-stream');
Grid.mongo = mongoosedb.mongo;

mongoosedb.Promise = global.Promise;
mongoosedb.connect("mongodb://localhost/promin");

var conn = mongoosedb.createConnection("mongodb://localhost/promin");
//var conn = mongoosedb.connection;

conn.once('open', function(){
  var gfs = Grid(conn);
  app.set('gridfs', gfs);
  app.set('grid', Grid);
})

When I set the writestream.on('error' , function() ...) nothing is happening too ...

What I did wrong ?

mvaldesdeleon commented 7 years ago

You seem to be passing the connection object to the Grid constructor, which according to the examples should be provided with the db object that can be accesible, in your code, at conn.db.

Maybe this is the cause?

Neewd commented 7 years ago

Oh thanks you very much.

It seems I tried in the first place and that wasn't working so I just left this solution but maybe it was not working for some other reason.

TY !

stefano-lupo commented 6 years ago

Wow, I was doing the exact same thing and it was causing a whole host of problems.

I have some boiler plate express code that I had been using that looks like:

mongoose.connect(dbURL);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   ...
   const gfs = Grid(db, mongoose.mongo);          // BAD!!!
   const gfs = Grid(db.db, mongoose.mongo);     // Terrible variable names but works
});

However my db variable was actually just a mongoose.connection object and thus I was passing that to the Grid constructor.

Using db.db (or better yet some sensible variable names solves the problem).

Thanks!