我在node.js服务器上编写了一个函数,该函数将使用gridfs-stream模块将来自MongoDB的文件发送到客户端(Web浏览器)。
我收到以下错误:
MongoError: file with id 5c4b74736202ee1ec8e98c5c not opened for writing
我一开始以为我传递给服务器的_id读取不正确,但事实并非如此。另外,服务器能够在MongoDB上检查是否存在带有相应_id的文件。
app.get('/tlcFichier', (req, res) => {
// Check file exist on
var filename = req.query.filename;
var id = req.query._id;
console.log(id);
console.log(filename);
const mongoURI = 'mongodb://10.182.41.184:27017/pokemon'
//Connect to the database
var conn = mongoose.createConnection(mongoURI);
conn.once("open", function (callback) {
console.log("Connection Succeeded");
//Init stream
gfs = Grid(conn.db,mongo);
gfs.collection('fs.files');
gfs.exist({ _id: id }, function (err, found) {
if (err) return handleError(err);
found ? console.log('File exists') : console.log('File does not exist');
if (found) {
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
var readstream = gfs.createReadStream({ _id: id });
readstream.pipe(res);
}
});
});
});
应该将文件下载到我的客户端上,但事实并非如此。