Skip to content Skip to sidebar Skip to footer

Appending Objects To An Array Within A Parent Object

I'm building a post request API using Express and I would like to return a JSON response back to the client containing an array of each record the provided, with an additional bool

Solution 1:

As I've just answered in other similar question, the problem is the data is being collected, but it's being sent before it's joined up together.

As you do request.forEach(async (record) => {, the async part tells your code not to wait, so even before the request.forEach loop is done, res.json(client_response) runs, when client_response is yet just an empty array. There are dozens of ways you can solve it. I can even think of the dumbest ones.

But here comes a good one:

// Start by saying your whole function is an async one
router.post('/api/v1/test', async (req, res) => {
    ... // (Your code comes here)
    
    // A better way to do the loop
    //for(const record of request){
    // Object deconstruction is awesome
    for(const { name, tech } of request){
        try{
            const rec = new testing({ name, tech })
            
            // Here, now all the function waits for this next line
            const a1 = await rec.save()
            var data = new Record_response(name, tech, true)
            client_response.partners.push(data)
        }catch(err){
            var data = new Record_response(name, tech, false)
            client_response.partners.push(data)
        }
    }
    
    // So the client_response has finally something!
    res.json(client_response)
});

Post a Comment for "Appending Objects To An Array Within A Parent Object"