1

TypeError: Cannot read property 'readPreference' of undefined

  E:\CapstoneProject\Express_ws\FoodCourtServer\node_modules\mongodb\lib\gridfs\grid_store.js:134
    this.options.readPreference || db.options.readPreference || ReadPreference.primary;
                                              ^

TypeError: Cannot read property 'readPreference' of undefined
    at new GridStore (E:\CapstoneProject\Express_ws\FoodCourtServer\node_modules\mongodb\lib\gridfs\grid_store.js:134:47)
    at new GridWriteStream (E:\CapstoneProject\Express_ws\FoodCourtServer\node_modules\gridfs-stream\lib\writestream.js:64:16)
    at Grid.createWriteStream (E:\CapstoneProject\Express_ws\FoodCourtServer\node_modules\gridfs-stream\lib\index.js:42:10)
    at E:\CapstoneProject\Express_ws\FoodCourtServer\routes\register.js:108:31
    at Immediate._onImmediate (E:\CapstoneProject\Express_ws\FoodCourtServer\node_modules\multer\lib\make-middleware.js:53:37)
    at runCallback (timers.js:793:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5

Server code (register.js)

var mongoose = require('mongoose');
var multer = require('multer');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var Readable = require('stream').Readable;
var GridFsStorage = require('multer-gridfs-storage');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27050/FoodCourtDatabase');
var conn = mongoose.connection;

conn.once('open', function () {
    console.log('Connected to DB.');
});
conn.on('error', function (err) {
    console.log('Connection error', err);
});

var RegisteredUserApi = require('../data/FoodCourtApi');
var express = require('express');
var router = express.Router();

// var busboy = require('connect-busboy');
// var app = express();
// app.use(busboy());

var gfs = Grid("FoodCourtDatabase");

var storage = GridFsStorage({
    url: 'mongodb://localhost:27050/FoodCourtDatabase',
    gfs: gfs,
    file: function (req, file) {
        console.log('file : '+JSON.stringify(file,null,4));
        return { filename: req.body.name };
    }
});

// multer settings for single upload
var upload = multer({
    storage: storage
}).single('profilepict');

//This route is only for testing
router.get('/', function (req, res) {
    res.json({ Hi: 'karthik' });
});

router.post('/loginvalidation', function (req, res) {
    var loggedInUser = {};
    loggedInUser.partnerId = req.body.partnerId;
    loggedInUser.password = req.body.password;
    RegisteredUserApi.validateLoggedInUser(loggedInUser, function (err, data) {
        // res.end();
        if (err) {
            console.log(err);
            res.status(500).json({ error: "login validation failed", err: err });
        } else {
            res.json(data);
        }
    });
});

router.get('/fetchprofiledetails/:id', function (req, res) {
    RegisteredUserApi.getProfileDetails(req.params.id, function (err, data) {
        if (err) {
            res.send(err);
        } else {
            res.json(data);
        }
    });
});

router.post('/uploadprofile', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            return res.status(400).json({ message: 'Upload Request Validation Failed' });
        } else if (!req.body.name) {
            return res.status(400).json({ message: 'No Picture name in request body' });
        }
        var picName = req.body.name;
        // convert buffer to readable stream
        var readableTrackStream = new Readable();

        readableTrackStream.push(req.file.buffer);
        readableTrackStream.push(null);

        var writestream = gfs.createWriteStream({ filename: picName });
        var id = writestream.id;
        readableTrackStream.pipe(writestream);

        writestream.on('error', function (err) {
            return res.status(500).json({ message: 'Error uploading file ' });
        }).on('finish', function () {
            return res.status(201).json({ message: 'File uploaded successfully, stored under Mongo ObjectID ' + id });
        });
    });
});

module.exports = router;

Postman Request

Request payload in postman

I am trying to upload an image using multer and multer-gridFs-Storage, but was facing this issue. I was stuck at this point since two days. Don't know the rootcause of the issue. It seems at the point of createWriteStream i am getting this error in console. Any suggestions?

devconcept
  • 3,665
  • 1
  • 26
  • 40
karthik_varma_k
  • 353
  • 4
  • 26
  • According to the error description, I think that you need to pass the "mode" (r, w or w+) option to the GridFsStorage constructor along with the URL, gfs and the file. The error is very much related to it. Please check [http://mongodb.github.io/node-mongodb-native/api-generated/gridstore.html](this link). You need to dig in the source or multer-gridfs-storage to check how it can be passed as I didn't find anything in its readme. – XCEPTION Apr 16 '18 at 12:36
  • I added the mode in createWriteStream as below : var writestream = gfs.createWriteStream({ filename: picName, mode:'w' }); – karthik_varma_k Apr 16 '18 at 13:57
  • still the same error (: – karthik_varma_k Apr 16 '18 at 13:59
  • The `gfs` property in the muster-gridfs-storageis not part of the [API](https://github.com/devconcept/multer-gridfs-storage/blob/master/README.md). BTW this library already support mongoose connections. – devconcept Nov 27 '18 at 17:03

2 Answers2

0

It seems that Gridfs is not compatible with new Mongoose versions greater than 5.0.0. So try using versions less then that, then everything will work fine.

0

Use this :

const GridFsStorage = require('multer-gridfs-storage').GridFsStorage;

instead of

var GridFsStorage = require('multer-gridfs-storage');