Gridfs和猫鼬文件上传 [英] Gridfs and mongoose file upload
问题描述
我在上载gridfs文件时遇到了问题. 基本上,我会收到这个奇怪的错误,但是我还没有找到解决此问题的解决方案.
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)
我使用的是Mongoose版本4.11.12和Gridfs-stream版本1.1.1
有人知道应该怎么做才能使此功能正常工作吗?
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?
推荐答案
看起来像mongoose.connection.db
并没有提取数据库名称,因为它可能在连接字符串上丢失,您的连接字符串应类似于'mongodb://username:password@host:port/database?options...'
,其中数据库是您要连接的数据库.
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.
或者您可以替换
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
使用
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs("myDatabase", mongoDriver);
这篇关于Gridfs和猫鼬文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!