使用GridFSBucket的openDownloadStream时出现文件未找到错误

4

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

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,但是出现了同样的错误。有没有人猜测我在这里做错了什么?
注意:代码可能看起来不太优化,比如声明了两次bucket,暂时请忽略它,一旦它工作起来,我会进行更正。

1
你能检查一下是否使用了 openDownloadStreamByName 吗?因为如果你正在使用文件名,那么应该使用它。 - Aritra Chakraborty
@AritraChakraborty,那个已经过时了,不是吗?他们在这里说(http://api.mongodb.com/java/current/com/mongodb/client/gridfs/GridFSBucket.html) - eduPeeth
您正在查看Java API文档。这是node js的最新v3.1 API文档。 - Aritra Chakraborty
2
@AritraChakraborty,嘿我的错。并且10/10指出这一点。 openDownloadStreamByName有效,我引用了错误的链接混淆了我。非常感谢。 - eduPeeth
酷,让我把它作为答案发布给其他“迷失的灵魂” :-p - Aritra Chakraborty
3个回答

6
根据API文档这里的说明,为了使用filename作为参数,您应该使用:
openDownloadStreamByName(filename, options)

不是使用openDownloadStream。openDownloadStream需要文件的id


3

如果您已经调用了openDownloadStream并仍然遇到文件未找到的错误,且您确定id是正确的,另一个可能的解释是您没有传递ObjectId类型。

在我的情况下,我传递的是一个id字符串,而不是一个ObjectId类型的id。

bucket.openDownloadStream(mongoose.Types.ObjectId(id));

vs

bucket.openDownloadStream(id);

0
以下代码对我来说有效:
const { ObjectId } = require('mongodb');

bucket.openDownloadStream(new ObjectId(id));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接