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: 6501df383452b6a687eb89c6
channelID: "ENR6318ahecz"
voiceRecordID: "6501df352839b6a687eb89c4"
timeStamp: 1694676496005
_id: 6501df783439b6a687da89ca
channelID: "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);
.....
server.post('/upload', async (req, res) => {
try {
.....
const fileId = "some-random-string";
// Create a new blog 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.







