title: return avg value in typeorm
body: <p>I work at an project with typeorm.
  In my project I have these entities:
  Course.ts</p>
  <pre><code>export class Course extends DefaultBaseEntity {
      @Column({name: &quot;course_name&quot;})
      courseName: string;
      @Column({name:&quot;discipline&quot;})
      discipline: string;
  
      @Column({default: 0}) rating: number;
  }
  </code></pre>
  <p>and RatingsCourse.ts</p>
  <pre><code>export class CoursesRatings extends BaseEntity {
      @PrimaryGeneratedColumn({type: &quot;bigint&quot;})
      public id: number;
  
      // other columns defined here
      @Column({type: &quot;bigint&quot;})
      userId: number;
  
      @Column({type: 'bigint'}) courseId: number;
  
      @Column() rating: number;
  }
  </code></pre>
  <p>the idea it's every course has ratings. when I add a new rating I want to save in the rating field from Course the average ratings value from CoursesRatings
  I code something like this :</p>
  <pre><code>await CoursesRatings.create({
              courseId: ratingBody.courseId,
              userId: user.id,
              rating: ratingBody.rating
          }).save();
          const ratingsObjects = await CoursesRatings.find({
              where: {
                  courseId: ratingBody.courseId,
                  userId: user.id
              },
              select: [&quot;rating&quot;]
          });
          const ratings: number[] = ratingsObjects.map(x =&gt; x.rating);
          const avgRating = ratings.reduce((a, b) =&gt; a + b) / ratings.length;
          const course = await Course.findOne(ratingBody.courseId);
          course.rating = Math.fround(avgRating);
          await course.save();
  </code></pre>
  <p>but it take some time.
  I want to know how to optimize this code. I appreciate any help. Thanks!</p>