0

我正在尝试将上传的文件(例如图像)写入 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);
      }
  });
 });


});

我猜这与我调用dbas有关,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();
});
4

1 回答 1

0

我的语法不正确,var Grid = require('gridfs-stream');很容易修复。

于 2015-07-20T20:23:01.107 回答