Mongodb: получение большого файла с использованием потока - PullRequest
0 голосов
/ 11 сентября 2018

Я использую grid-stream и библиотеку girdFsStorage для получения изображения из mongodb.

Я загрузил изображение в БД, все в порядке, но когда я попытался получить изображение из БД, не удалось.

Я ожидал, что 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))

и это мой код для получения изображения из 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'
         });
      }
    });
});

1 Ответ

0 голосов
/ 12 сентября 2018

Это было потому, что я не использовал

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

...