I have uploaded a PDF file and its metadata UserId with multer-gridfs-storage and Node.js, and I can query files out by const file = gfs.find({ metadata: { UserID: req.params.UserId } }), console.log (files) shows the files.
But I got problem to display the file with
const readstream = gfs
.openDownloadStreamByName(req.params.filename)
.pipe(res); ......
The partial code is as
const storage = new GridFsStorage({
// url: (mongoURI, { useUnifiedTopology: true}),
url: mongoURI,
options: { useNewUrlParser: true, useUnifiedTopology: true },
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString("hex") + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: "uploads",
metadata: req.body,
};
resolve(fileInfo);
});
});
},
});
const upload = multer({ storage });
//-------------------------------------------Query files------
router.get("/pdf/:UserId", (req, res) => {
const file = gfs
.find({ metadata: { UserID: req.params.UserId } })
.toArray((err, files) => {
// Check if file
if (!files || files.legnth === 0) {
return res.status(404).json({
err: "No file exists",
});
}
console.log({ files }); // Yes, work OK. how to extract files to get the filename ?
const readstream = gfs
.openDownloadStreamByName(req.params.filename) // code for other query
.pipe(res);
});
});
How to get filename from files { }object to replace req.params.filename?