I need to rebuild the JS (server) code to write to a DB collection in MongoDB Atlas.
Since I am encountering some problems on the way, I decided to write this post and see if someone could give me some help by having a new look at it.
First, here is how the collection looks:
_id: 6501df383452b6a687eb89c6channelID: "ENR6318ahecz"voiceRecordID: "6501df352839b6a687eb89c4"timeStamp: 1694676496005_id: 6501df783439b6a687da89cachannelID: "ENR6318ahecz"voiceRecordID: "6501df712219b6a687eb89c8"timeStamp: 1691921560338.....
I have this scheme working in TypeScript code, to access (by reading) the collection:
const speakSchema = new Schema({ channelID: { type: String, required: true }, voiceRecordID: { type: String, required: true }, timeStamp: { type: Number, required: true } }) interface SpeakDoc extends Document { channelID: string voiceRecordID: string timeStamp: number } interface SpeakModel extends Model<SpeakDoc> {} const theModel = (models && models.Voice) ? (models.Voice as SpeakModel) : mongoose.model<SpeakDoc, SpeakModel> ('Voice',speakSchema,'mycollection')
Then I have code like the one below to read the collection:
await connectMDB() try { const theResult = await theModel .find({channelID:channel}) return theResult } catch (error) { console.error("Error in Read-Function:", error); throw error; // Rethrow the error to propagate it. }
All the above works perfectly for now.
Next comes the problem. I need to be able to insert new records in the collection using JS. The code is in express server.
Here is what I have at this point, but it is not working:
.... const {Schema,model} = mongoose; const vxSchema = new Schema({ channelID: String, voiceRecordID: String, timeStamp: Number }, { versionKey: false /* This gets rid of the "__v: 0" that is otherwise added to the collection. */ }); const VxIns = model('VxIns', vxSchema); ..... function saveAudioToGridFS(audioBlob) { return new Promise((resolve, reject) => { const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db), upldName = getAudioName() const writeStream = gridFSBucket.openUploadStream(upldName); writeStream.on('close', (file) => { if (file !== undefined) { resolve(file._id); // Return the GridFS file ID } }); writeStream.on('finish', (file) => { if (file !== undefined) { 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 */ server.post('/upload', async (req, res) => { try { if (!req.body.audio) { return res.status(400).json({ message: 'No audio data uploaded.' }); } console.log("Before saveAudioToGridFS") const audioBuffer = Buffer.from(req.body.audio, 'base64'), fileId = await saveAudioToGridFS(audioBuffer); console.log("fileId=",fileId) // Create a new VX object: const newRcd = new VxIns({ channelID:req.body.channel, voiceRecordID:fileId, timeStamp: new Date().getTime() }); // Insert the newRcd in our MongoDB database await newRcd.save(); res.json({ fileId }); } catch (error) { console.error(error); res.status(500).json({ message: 'An error occurred during upload.', error: JSON.stringify(error) }); } });
Can someone see at a glance what is, or what could be, wrong in this last chunk of code ? Knowing that the first presented TypeScript code is working.
P.S. I just noticed that the call to saveAudioToGridFS, while saving data in the database as expected does not return the fileId as it should.