Reputation: 447
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' }
Upvotes: 0
Views: 730
Reputation: 341
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);
Upvotes: 0
Reputation: 4802
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);
Upvotes: 3
Reputation: 452
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);
Upvotes: 0