我可以使用GridFSBucket的openDownloadStream上传一个文件,并看到该文件已上传并在songs.files chunks下可见。但由于某种原因,得到以下错误,而试图下载它-
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,请暂时忽略它,因为一旦它工作,我会纠正它。
3条答案
按热度按时间cld4siwp1#
根据这里的API文档,为了使用
filename
作为参数,您应该使用而不是
openDownloadStream
。openDownloadStream获取文件的id
。hsvhsicv2#
另一个可能的解释是,如果你已经在调用openDownloadStream,但仍然遇到FileNotFound错误,并且你100%的id是正确的,那就是你没有传递ObjectId类型。
在我的例子中,我传递了一个id string,而不是一个id作为ObjectId。
vs
w6lpcovy3#
以下代码适用于我: