0

i am new with using mongodb and node am trying to loop through an array of objects from my database and display only the objects using a res.json, in my console.log it displays all the object, but in my postman using res.json it displays only one object please help

MY CODE

const course = res.GetUserDT.coursesHandled;
  for (let index = 0; index < course.length; index++) {
            console.log(course[index]);
        }
const course = res.GetUserDT.coursesHandled;
  for (let index = 0; index < course.length; index++) {
            res.json(course[index]);
        }

my console output


{ courseCode: '2103' }
{ courseCode: '2012' }
{ courseCode: '2062' }

my postman output


{ courseCode: '2103' }

3 Answers 3

3

Hi and welcome to Stackoverflow.

The Problem here is that res.json() sends a an immidiate response to the requestor - meaning a response is sent already within the first iteration of your for-loop.

I am also wondering why you need that loop - as you are not doing anything within it. So why don't you just send the array immidiately like so:

res.json(res.GetUserDT.coursesHandled);
Sign up to request clarification or add additional context in comments.

2 Comments

I missed that in my answer. This should definitely be the accepted answer if you are not doing any array modifications!
This is the perfect answer and should be included in the accepted ones.
0

You can only send res.json once.

To send all of them together you can create an array, push all the objects in the array and send it back as a response.

let arrayToReturn = []
for (let index = 0; index < course.length; index++) {
   arrayToReturn.push(course[index])
}
res.json(arrayToReturn);

Update

@David's answer is the most accurate solution i.e just directly send the array as a response instead of looping

res.json(res.GetUserDT.coursesHandled);

2 Comments

You're welcome but david's answer is more simple and accurate because there is no need for loop unless you need some modification.
it worked but how do i pull all the courses from the array and display as separate data
0

Assuming that is express, res.json() will send the data and end the response.

try something like:

 const responseArray = [];
 
 for (let index = 0; index < course.length; index++) {
    responseArray.push( course[index] ); 
 }
 res.json(responseArray);

Comments

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.