Map over Adonis Query Result on Server side

I have this code in my controller:

async courses({ params, request, response }) {
    const limit = params.limit || 4;
    let trends = await Trend.query()
      .select("course_id")
      .whereNotNull("course_id")
      .orderBy("view_date", "desc")
      .groupBy("course_id")
      .limit(limit)
      .fetch();
    console.log("trends", trends);

    const course_ids = [];

    trends.map(trend => {
      course_ids.push(trend.course_id);
    });

    const courses = await Course.query()
      .whereIn("id", course_ids)
      .fetch();

    return response.status(200).json(courses);
  }
}

I get the error: trends.map is not a function

So, if I return trends as a response to the client-side, it’s a valid array that I can map over. But on the server-side, it’s some weird shape with many private fields.

Question: How can I map over query results on the server, so I can pass it to the next query? Thanks.

That is because the result of your query ( trends) is not an array.

1 Like

Yeah. Found the answer in the docs: https://adonisjs.com/docs/4.1/serializers

The solution is to convert it to JSON: const trendsJson = trends.toJSON()

Now, it’s an array and .map works.

Thanks.

1 Like

That’s it, you got a hint and you did the rest by yourself :slight_smile: