Reputation: 83
I have ran into a problem with gridfs file upload. Basically I get this bizzare error and I have yet not found solution for solving this problem.
Here is my code that should deal with file upload:
var path = require('path');
var router = require('express').Router();
var mongoose = require('mongoose');
var serverConfig = require('../config.js');
var multiparty = require('connect-multiparty')();
var fs = require('fs');
var GridFs = require('gridfs-stream');
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
router.post('/upload', multiparty, function(req, res){
console.log("file was posted");
var writestream = gfs.createWriteStream({
filename: req.files.file.name + Date.now(),
mode: 'w',
content_type: req.files.file.mimetype,
metadata: req.body
});
fs.createReadStream(req.files.file.path).pipe(writestream);
writestream.on('close', function(file){
res.status(200).json(file);
})
})
When trying to run my code, I get this error:
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument
new Grid(db, mongo)
Im using Mongoose version 4.11.12 and Gridfs-stream version 1.1.1
Does anybody know what should be done to get this thing working?
Upvotes: 0
Views: 4787
Reputation: 14436
Looks like mongoose.connection.db
is not pulling in the database name as it maybe missing on the connection string, your connection string should look like 'mongodb://username:password@host:port/database?options...'
where database is the database you want to connect to.
alternatively you can just replace
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
with
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs("myDatabase", mongoDriver);
Upvotes: 1