使用 GridFSBucket openDownloadStream 时找不到文件错误

File not found error when using GridFSBucket openDownloadStream

我能够使用 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 但同样的错误。有人猜到我在这里做错了什么吗?

注意 - 此处的代码似乎没有优化,例如两次声明存储桶,请暂时忽略它,因为一旦它起作用我会更正它。

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

openDownloadStreamByName(filename, options)

不是openDownloadStream。 openDownloadStream 需要 id 文件。

另一种可能的解释是,如果您已经在调用 openDownloadStream 并且仍然遇到 FileNotFound 错误,并且 100% id 是正确的,那么您没有传递 ObjectId 类型。

在我的例子中,我传递了一个 id string 而不是 id 作为 ObjectId。

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

bucket.openDownloadStream(id);