0

I'm retrieving documents from an array of _ids. However, the returned results are alphabetically sorted by _ids and I don't know why. How can I avoid this and maintain the order the _ids had in the input array?

Somewhere in this function, the wrong sorting happens even tho I pass undefined for the sort step:

export async function getApprovedPopulatedResources(match?: mongoose.AnyObject, sort?: Record<string, 1 | -1>, page?: number, pageSize?: number) {

    let resourcesFilter = [];

    if (sort) resourcesFilter.push({ $sort: sort })

    if (page && pageSize) {
        resourcesFilter.push({ $skip: (page - 1) * pageSize });
        resourcesFilter.push({ $limit: pageSize });
    }

    let aggregationResult = await Resource.aggregate()
        .match({
            approved: true,
            ...match
        })
        .lookup({
            from: "resourcevotes",
            localField: "_id",
            foreignField: "resourceId",
            as: "votes",
        })
        .facet({
            resources: resourcesFilter,
            totalCount: [{ $group: { _id: null, count: { $sum: 1 } } }]
        }).exec();

    const resourcesPopulated = await Resource.populate(aggregationResult[0].resources,
        [
            { path: "submittingUser" },
            { path: "lastUpdatingUser" },
        ]
    );

    const totalCount = aggregationResult[0].totalCount[0]?.count || 0;

    const result = {
        resources: resourcesPopulated,
        totalCount: totalCount,
        pageCount: Math.ceil(totalCount / (pageSize || totalCount)),
    };

    return result;
}

The following is the calling site. result.resources is ordered by _id (alphabetically). I don't want this.

const resourceIds = [...] // This has the correct order of _ids.

const result = await getApprovedPopulatedResources( // this returns the wrong order of resources
    { _id: { $in: resourceIds } },
    undefined,
    page,
    pageSize
);
Florian Walther
  • 6,237
  • 5
  • 46
  • 104

0 Answers0