0

I'm trying to insert a few documents to a mongoose collection called Slots with a post method (testing via Postman). In my code, after insertion, I want to print in the console the inserted documents. The code below adds correctly in the database but doesn't print the added new slots in the console. instead, an empty array is printed in the console

My logic: I understand that the .save() function returns the new document inserted whenever it's called. I'm trying to save that document and push it in an array called slotsDisplay, so that after the forEach function is done, I can print the documents inserted correctly. I added async-await to ensure that I have to wait till the record is fully inserted. Can someone help me explain what goes wrong here and if my logic is even correct.

app.post('/addSlot', async (req, res) => {
try {
    let slotArray = req.body;
    let slotArraySize = slotArray.length;
    let slotsDisplay = [];

    slotArray.forEach(async (doc, index) => {
        let slotEntered = new Slots({
            time: doc.time,
            typeOfSlot: doc.typeOfSlot,
            academic_mem_id: doc.academic_mem_id,
            course_id: doc.course_id,
            tut: doc.tut,
            location: doc.location
        })

        let topush = await slotEntered.save()
        slotsDisplay.push(topush)
    })
    res.json(slotsDisplay)
}
catch (error) {
    console.log("index: " + index + " Error: " + error)
    res.json(error);
}
});
Rana
  • 31
  • 3

0 Answers0