我正在尝试将上传的文件(例如图像)写入mongodb数据库。但是,当我尝试初始化gridfs-stream时,我得到一个类型错误。这是我的代码:
var mongo = require('mongodb');
router.post('/createpost', cpUpload, function(req,res) {
var db = req.db;
var gfs = Grid(db,mongo);
var file = req.file;
var fileId = new ObjectId();
var writestream = gfs.createWriteStream({
filename: file.originalname,
mode: 'w',
content_type: file.mimetype,
metadata: req.body.postText,
});
fs.createReadStream(file.path).pipe(writestream);
writestream.on('close', function(file) {
res.send("Succcess!");
fs.unlink(file.path,function(err) {
if (err) {
console.log("Error: ", err);
console.log("DELETED: ", file.path);
}
});
});
});
我猜这与我调用db
为req.db
有关,但我使用app.js中的代码使路由器文件可以访问该数据库
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/test-api');
app.use(function(req,res,next) {
req.db = db;
req.mongo = mongo;
next();
});
答案 0 :(得分:0)
var Grid = require('gridfs-stream');
的语法不正确,非常简单。