1

I am trying to send an array of document IDs as JSON response but the array I obtain as the response is empty. How can I make sure the array is populated first by the document IDs before it is sent as the response?

exports.createItem = async (req,res,next) => {
    let itemsIds = [];
    req.body.forEach( async element => {
        let doc = await Item.findOneAndUpdate({
            type: element.type,
            color: element.color,
            size: element.size
            }, {
            $inc:{stock: element.stock}
            }, {upsert:true, new: true});   
        itemsIds.push(doc._id);
        });
    res.status(200).json({
        success: true,
        itemsIds: itemsIds
    })
}

I want to make sure the res.status(200).json({...}) method runs only after all the doc ids are pushed to the mongo DB. Right now I just get the itemsIds as [ ] in the response. How I can make sure itemsIds array is populated by the doc ids first before sending the response?

1 Answer 1

2

The forEach loop contains a callback function, where we should not use async await, use the for of loop to await for the result, push it into the array and then send the response.

exports.createItem = async (req,res,next) => {
    let itemsIds = [];
    for (var element of req.body) {
        let doc = await Item.findOneAndUpdate({
            type: element.type,
            color: element.color,
            size: element.size
            }, {
            $inc:{stock: element.stock}
            }, {upsert:true, new: true});   
        itemsIds.push(doc._id);
    }
    res.status(200).json({
        success: true,
        itemsIds: itemsIds
    })
}
Sign up to request clarification or add additional context in comments.

3 Comments

@SagarChilukuri i have updated the answer, please find the answer.
It works! Thank you. I will mark this answer as the best answer but can you please explain why this method works? Why does it work using for loop instead of forEach() ?
Once you give a function to forEach, it takes it as a asynchronous call, and its not handled by the main thread any more, so the main thread starts working on the next line, In your case it send the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.