Mongodb:使用流获取大文件

问题描述 投票:0回答:1

我正在使用grid-stream和girdFsStorage库从mongodb获取图像。

我上传图像到数据库是好的,但当我试图从数据库获取图像失败。

我期待gfs.files.findOne({ filename: req.params.filename }, (err, file) => {...}上的db.collection,但是返回了this.db.collection。有任何想法吗?

TypeError:this.db.collection不是函数

这是我的数据库连接

 let db =  mongoose.connect(init.mongoUrl)
  .then(() => console.log('Connected to MongoDB...'))
  .catch(err => console.error(('Could not connect to MongoDB...\n'), err))

这是我从db获取图像的代码

// Init stream
const gfs = Grid(db, mongoose.mongo);

api.get('/image/:filename', (req, res) => {
    gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
      // Check if file
      if (!file || file.length === 0) {
        return res.status(404).json({
          err: 'No file exists'
        });
       }

      // Check if image
      if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
        // Read output to browser
        const readstream = gfs.createReadStream(file.filename);
        readstream.pipe(res);
      } else {
        res.status(404).json({
          err: 'Not an image'
         });
      }
    });
});
mongodb mongoose gridfs gridfs-stream
1个回答
0
投票

因为我没用过

gfs.collection( '上传');

on .once('open',()=> {...})

// Init gfs
let gfs;

conn.once('open', () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('uploads');
});

你可以在这里看到我的例子:https://github.com/qkreltms/mongodb_simple_file_upload_to_db_example/blob/master/app.js

关于.collection():https://github.com/aheckmann/gridfs-stream/blob/c394e050d066a5c81c6dcdddad186b08a93d5f1f/lib/index.js#L75

© www.soinside.com 2019 - 2024. All rights reserved.