4

I'm trying to have a play with gridfs-stream but I'm having issues posting an image file to my upload controller. When it tried to create the write stream is returns grid.mongo.ObjectID is not a constructor at new GridWriteStream

I've searched around and not really found anything that helps me with this issue, and debugging hasn't turned anything up I can work with, this is all new technologies for me.

Here's my code:

const router = require('express').Router();
const database = require('../config/database');
var mongoose = require('mongoose');

var Grid = require('gridfs-stream');
Grid.mongo = mongoose.connection;
var gfs = new Grid("db", mongoose.mongo.db);


router.get('/', function(req, res) {
    res.send("Greetings");
});

router.post('/img', function(req, res) {
    var part = req.files.fileField;

    var writeStream = gfs.createWriteStream({
        filename: part.name,
        mode: 'w',
        content_type:part.mimetype
     });

    writeStream.on('close', function() {
            return res.status(200).send({
            message: 'Success'
        });

        writeStream.end();
    });
});

module.exports = router;

I have also tried passing just mongoose.mongo to the gfs object as the second argument but that also threw an error about being able to read readPreferences of undefined

geolaw
  • 412
  • 1
  • 12
  • 26
  • 1
    You have invalid arguments. Should be `var conn = mongoose.connection; var gfs = new Grid(conn.db, mongoose.mongo);`. Ideally you *"should"* be awaiting the actual connection along the lines of `var conn = await mongoose.connect();` or `mongoose.connect().then( conn => /* remaining code */)` or even `mongoose.connect(, conn => /* remaining code */)` depending on which flavor you prefer. – Neil Lunn Apr 15 '18 at 03:48
  • In short your current "string" of `"db"` is not an object which is valid for that argument. Look at the [documentation](https://github.com/aheckmann/gridfs-stream) and also look at the [Connections](http://mongoosejs.com/docs/connections.html) documentation for mongoose. – Neil Lunn Apr 15 '18 at 03:50
  • Bingo! Okay so initally my code was as you said, however it didn't occur to me that the instantiation was taking place before the connection was made to the db. I've reverted my code and moved the calls to the event listener. For some reason the image is not uploading however the issue in this question has been fixed. Thank you. – geolaw Apr 15 '18 at 03:58

0 Answers0