Customized data populations from fetch requests is sorting randomly

System Information
  • Strapi Version: 3.2.4
  • Operating System: macOS High Sierra 10.13.6
  • Database: SQLite 5.0.0, PostgreSQL 8.4.1
  • Node Version: 12.18.4
  • NPM Version: >=6.0.0
  • Yarn Version: 1.22.4

Problem:
Using the Strapi default controller my json response is sorted by id, but using a custom controller, the json response became sorted randomly.

Context:
My Strapi app has posts and each post has many comments. I have a custom controller for in post/controllers/posts.js to fetch customized relational data from the comments collection (the default only fetched comments.author.id but I wanted comments.author.username):

async find(ctx) {
        let entities;
        if (ctx.query._q) {
          entities = await strapi.services.post.search(ctx.query);
        } else {
          entities = await strapi.services.post.find(ctx.query, ['author', 'comments', 'comments.author', 'goals']);
        }

        return entities.map(entity => sanitizeEntity(entity, { model: strapi.models.post }))
},

I got this json response from the custom controller for my /posts endpoint:

[
  {
    "id": 7,
    "title": "Testing post 2",
    "content": "Testing content",
    ...
    "comments": [
      {
        "id": 28,
        "content": "...",
          ...
        },
      {
        "id": 31,
        "content": "...",
          ...
        },
      {
        "id": 27,
        "content": "...",
          ...
        },

The weird thing is, the relational data from comments collection is now sorted in a seemingly random order, with the ids like this: 28, 31, 27, 24, 17, 23, 21, 19, 29, 18, 25, 32...

Using the default controller, it sorts by id just fine, but why does my custom controller sort in random order? Where should I start to look to debug something like that? Any pointers in the general direction is appreciated! :slight_smile:

Did you manage solve this? I am stuck with this problem too right now.

In the end I sorted it on frontend, using lodash .orderBy

Thanks, yeah I actually did that too in the end