Nodejs proper mapping with array

Viewed 38

I don't know why i cant get all data of subject that relate from student, The only data that display on response is the last id of student model, I tried to put console.log(subject) and i get the desired result but i dont know why i cant display it on response

const results = {
     student: null,
     subject: null,
}
const student = await StudentModel.getById(id)
if(student){
   for(let i = 0; i<=student.length - 1; i++){
     subject=  await SubjectModel.getByStudentId(student[i]._id)
     console.log(subject)
     subject.append(subject)
     
   }
}
results.subject= subject
res.json(data)

current result

student:[
   {
      id: 1,
      description: student 1
   },
   {
      id: 2,
      description: student 2
   }
],
subject:[
   {
      studentid: 2,
      description: subject 2
   }
]

desired result

result

student:[
   {
      id: 1,
      description: student 1
   },
   {
      id: 2,
      description: student 2
   }
],
subject:[
   {
      studentid: 1,
      description: subject 1
   },
   {
      studentid: 2,
      description: subject 2
   }
]

Update when I tried to implement append i received this error

error: uncaughtException: subject.append is not a function

1 Answers

As mentioned by @Dave in the comments, you are not appending the values instead overriding it. You should do something like:

// If students is a list
const students = await StudentModel.getById(id); 
const subjects = [];
for (let i = 0; i <= students.length - 1; i++) {
    const subject = await SubjectModel.getByStudentId(students[i]._id)
    console.log(subject);
    subjects.push(subject);
}

const data = {
    students, subjects
}

res.json(data);

The code above will work fine, but as per my understanding if you are searching by id, there should not be more than one record, so your getById() function should give you the record or null if the record doesn't exist. If this is the case you might not even need a loop. All you can do is:

// If students is an object
const student = await StudentModel.getById(id);
const subject = student ? await SubjectModel.getByStudentId(student._id) : null;

const data = {
    students, subjects
}

res.json(data);
Related