Reputation: 11755
I would need a second pair of eyes to confirm (or deny) that the following function is working to save an audio blob to a mongo database using GridFS. The fact is that as far as I recall, it has been working, but now it fails to return the file._id. So I wonder what happened or what I am missing.
function saveAudioToGridFS(audioBlob) {
return new Promise((resolve, reject) => {
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db),
upldName = getAudioName() // Getting a file name.
const writeStream = gridFSBucket.openUploadStream(upldName);
writeStream.on('close', (file) => {
// For unknown reasons, the value of file is always undefined here.
if (file !== undefined) {
console.log("file=(saveAudioToGridFS)",file)
console.log("file._id=",file._id)
resolve(file._id); // Return the GridFS file ID
}
});
writeStream.on('finish', (file) => {
// For unknown reasons, the value of file is always undefined here.
if (file !== undefined) {
console.log("file=(finish)",file)
console.log("file._id=",file._id)
resolve(file._id); // Return the GridFS file ID
}
});
writeStream.on('error', (error) => {
reject(error);
});
// Convert the Blob into a readable stream using streamifier
const readableStream = streamifier.createReadStream(audioBlob);
// audioBlob.pipe(writeStream);
readableStream.pipe(writeStream);
});
} /* End of saveAudioToGridFS */
The function above is called in server code like this:
server.post('/upload', async (req, res) => {
try {
if (!req.body.audio) {
return res.status(400).json({ message: 'No audio data uploaded.' });
}
const audioBuffer = Buffer.from(req.body.audio, 'base64'),
fileId = await saveAudioToGridFS(audioBuffer);
.....
} catch (error) {
res.status(500).json({
message: 'An error occurred during upload.',
error: JSON.stringify(error)
});
}
});
When I try it I can check that data is written to the DB, but the file._id is not returned.
Upvotes: 0
Views: 69