node.js - 使用 GridFSBucket openDownloadStream 时出现文件未找到错误

标签 node.js mongodb mongoose filestream gridfs

我可以使用 GridFSBucket 的 openDownloadStream 上传文件,并看到该文件已上传并在ongs.files block 下可见。但由于某种原因,在尝试下载时出现以下错误 -

Caught exception: Error: FileNotFound: file def1.txt was not found

我的代码是 -

var express = require('express');
var gridModule = express.Router();
var mongoose = require('mongoose');
var fs = require('fs');

gridModule.post('/', (req, res) => {
    console.log("::::grid");
    //const gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db);

    //const writeStream = gridfs.openUploadStream('test.dat');

    var gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });

    fs.createReadStream('./def.txt').
        pipe(gridfs.openUploadStream('def1.txt')).
        on('error', function (error) {
            assert.ifError(error);
        }).
        on('finish', function () {
            console.log('done!');
            process.exit(0);
        });

});

gridModule.get('/', (req, res) => {
    var gridfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
    });
    /* var bucket = new mongodb.GridFSBucket(db, {
        chunkSizeBytes: 1024,
        bucketName: 'songs'
      }); */

      gridfs.openDownloadStream('def1.txt').
        pipe(fs.createWriteStream('./def1.txt')).
        on('error', function(error) {
            console.log(":::error");
          assert.ifError(error);
        }).
        on('finish', function() {
          console.log('done!');
          process.exit(0);
        });
});

module.exports = gridModule;

我也尝试使用 ObjectId id 但出现同样的错误。有人猜我在这里做错了什么吗?

注意 - 代码在这里可能看起来没有优化,比如声明存储桶两次,请暂时忽略它,因为一旦它工作,我会纠正它。

最佳答案

根据API文档here ,为了使用 filename 作为参数,您应该使用

openDownloadStreamByName(filename, options)

不是openDownloadStream。 openDownloadStream 采用 id 文件的内容。

关于node.js - 使用 GridFSBucket openDownloadStream 时出现文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505049/

相关文章:

node.js - 如何在 Mongoose 中将数据保存到数组中?

windows - MongoDB中的这个错误 "No TransportLayer configured during NetworkInterface startup"是什么意思?

javascript - 等待 cli 中的 promise

scala - Casbah Scala MongoDB 驱动程序 - 嵌入式对象

node.js - 无法使用 Mongoose 连接到mongodb数据库

php - mongodb写关注

node.js - 如何对 keystonejs 模型进行单元测试?

node.js - 将 Pug 与 NodeJS 和 Webpack 结合使用

html - 广播实时网络摄像头流

node.js - 在 intellij ultimate 2017.1 中调试 Node/Express 应用程序