Gridfs and mongoose file upload

瘦欲@ 提交于 2019-12-08 13:29:25

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/46705438/gridfs-and-mongoose-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!