Sort by date field seems not to be working

I got a ContentType post with a Date field publishAt field.

Basically I have a custom publication date for some business logic.

I’m trying to get the up next post doing this query:

module.exports.getUpNextPost = async (ltDate, options = {}) => {
  const query = {
    ...options,
    content_type: "post",
    "fields.publishDate[lt]": ltDate
  };
  const { items } = await contentulClient.getEntries(query);
  const [upNextPost] = items;
  return upNextPost && upNextPost.fields ? upNextPost : null;
};

So, basically if I have a post entry foo I expect that the following code would make the trick:

const nextPost = await getUpNextPost(foo.fields.publishDate);

However this is not working properly.

Taking as reference the following posts screenshot:

When I try to get the up next for for the Vacations, Meditations, Humiliations: What We’re Listening To In July, I’m not getting neither Exclusive, Hear Matthew… or 10 Lovable Listens.

But another post which got 06/27/2016 12:00 PM +00:00 as publishDate.

Any guidance will be appreciated.

Hej @daguilar,

your parameters to the Contentful client currently only apply a search condition. This limits the result set to only show entries that are below the given datetime.
What you want is to have it ordered by the fields.publishDate as well, so that the first item is the one closest to the specified date.

This can be achieved by extending the query object with another key-value pair?

{
  ...options,
  content_type: "post",
  "fields.publishDate[lt]": ltDate
  order: '-fields.publishDate'
}

The minus sign inverses the order of the results, so that you have the items in a descending order.

Does this solve your question?
Best,
Stephan