找不到文件'当试图从mongodb获取gridFS文件时

时间:2018-05-29 12:01:13

标签: javascript node.js mongodb mongoose gridfs

我正在尝试读取我上传到mongodb的文件,并且我每次都获得file not found,当有明确的文件名称我试图在我的数据库中查找时。我使用this方法来实现gridfs

代码:

    let mongoose = require('mongoose');
    let gridfs = require('gridfs-stream');

    const express = require('express');
    const router = express.Router();

    mongoose.connect('mongodb://foo123.mlab.com:123456/db_name', {
        auth: {
          user: 'username',
          password: 'password'
        }
      })
      .then(() => console.log('connection successful'))
      .catch((err) => console.error(err));

    mongoose.Promise = global.Promise;
    gridfs.mongo = mongoose.mongo;
    let connection = mongoose.connection;

    connection.on('error', console.error.bind(console, 'connection error:'));

connection.once('open', () => {
    var gfs = gridfs(connection.db);
    router.post('/' ,(req, res) => {
        gfs.exist({ filename: '6866866-Tue-May-29-2018.jpg' }, function (err, file) {
            if (err || !file) {
                console.log(err)
                res.send('File Not Found');
            } else {
                let readstream = gfs.createReadStream({ filename: '6866866-Tue-May-29-2018.jpg' });
                readstream.pipe(res);
            }
        });
    })
})

module.exports = router;
来自db的

文件,我试图获取:

{
    "_id": {
        "$oid": "5b0d2xxxxxxxxxx14cfb118"
    },
    "length": 641142,
    "chunkSize": 261120,
    "uploadDate": {
        "$date": "2018-05-29T10:39:37.568Z"
    },
    "md5": "c9bc6d74axxxxxxxxxxxx25a70",
    "filename": "6866866-Tue-May-29-2018.jpg",
    "contentType": "image/jpeg"
}

0 个答案:

没有答案