Search code examples
node.jsmongodbgraphqlnestjstypeorm

Find many does not work in NestJs + mongoDB + TypeOrm + GraphQL


I have a Nest Js application that has 2 modules: Lesson and Student I want to have a list of my lessons and one field in my entity is students. I found that i have to use @ResolveField() decorator to bind student to my getAllLessons query so :

@ResolveField()
  async students(@Parent() lesson: Lesson) {
    const result = await this.studentService.getManyStudents(lesson.students);
    return result;
  }

also in my studentService:

async getManyStudents(studentIds: string[]): Promise<Student[]> {
    const result = await this.studentRepository.find({
      where: {
        id: In(studentIds),
      },
    });

    return result;
  }

but getManyStudents always returns an empty array

Note: I checked studentIds and its correct. I logged every incoming data and there was no problem

I found out that the problem comes from here:

 this.studentRepository.find({
      where: {
        id: In(studentIds),
      }

apparently it cannot find anything while i use In() from TypeOrm

Note: I tried

this.studentRepository.find({
      where: {
        id: studentIds[0],
      },

and it worked perfectly but i want to get all students not just the first one

Note: i cannot use $in, typescript yells:

this.studentRepository.find({
      where: {
        id: { $in: studentIds },
      },
    });
Object literal may only specify known properties, and '$in' does not exist in type 'FindOperator<string>'.

Solution

  • You can try with the QueryBuilder.

    this.studentRepository.createQueryBuilder("student")
    .where("student.id in(:...studentIds)", {studentIds})
    .getMany()