我可以使用 GridFSBucket 的 openDownloadStream 上传文件,并看到该文件已上传并在ongs.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 错误,并且 id 100% 正确,则说明您没有传递 ObjectId 类型。
就我而言,我传递的是 id string 而不是 id 作为 ObjectId。
bucket.openDownloadStream(mongoose.Types.ObjectId(id));
对
bucket.openDownloadStream(id);
以下代码对我有用:
const { ObjectId } = require('mongodb');
bucket.openDownloadStream(new ObjectId(id));