Sorting from a reference query

I have an experience database that contains a reference to a tracking database that keeps track of the most popular experiences. The experience database contains all the information pertaining to the experience it’s self. This includes city and state. What I would like to do is return an ordered list of the most popular experiences from a given state and render that data to a repeater. After much trial and error I was able to return the data from both databases, but I am unable to order the data that is passed back by number of times clicked. Here is my query:

wixData.query("Experiences").contains("state", "CA").include("data").descending("viewCounter").limit(2).find().then(res => console.log(res))

This just returns two items from the database but does not order them in descending order based on the viewCount from the referenced database. It more or less just returns the first two items that match the state.

When I log out res I see that the viewCounter I want to reference is returned in a data object that is on the returned information. Like so:

{
    city: "city",
    state: "CA",
    ...,
    data: {...data object}
}

I think this is the reason why I can not order by viewCounter; however I can not call data.viewCounter into the descending query.

I would like to avoid returning all the matching experiences and then mapping through them manually just to return two items. Is this possible?

Ok, first things first. You are querying one collection called Experiences , and the sorting method is going to be applied to this collection. The include method you use, is only there to grab the referenced item in another collection. You will have to sort the data that you queried manually, using an Array.sort() method. And your query is limited to 2 items only.

That’s what I was afraid of. But I imagine the built in descending and ascending methods would have the same time efficiency as calling array.sort on the returned data anyways