0

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

我将图像上传到 db 没问题,但是当我尝试从 db 获取图像时失败。

我预计 db.collection 会返回,gfs.files.findOne({ filename: req.params.filename }, (err, file) => {...} 但 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))

这是我从数据库获取图像的代码

// 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'
         });
      }
    });
});
4

1 回答 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

于 2018-09-12T08:07:38.943 回答