#How to sort a content collection by date?

1 messages · Page 1 of 1 (latest)

analog star
#

My content collections are currently sorted by file name, I want to sort them by pubDate. How to do this?

Getting the posts:

const allPosts = await getCollection('blog');

Frontmatter of posts:

pubDate: 2023-02-17
analog star
#

This worked:

allPosts.sort((a, b) => {
  const pubDateA = new Date(a.data.pubDate);
  const pubDateB: Date = new Date(b.data.pubDate);
  return pubDateB.getTime() - pubDateA.getTime();
});
sharp axle
#

if you use content collection, you can easily cast dates with zod using: z.date().default(() => new Date())

#

then you can simplify your code since you'll have guarantee that pubDate is an instance of Date such as:

allPosts.sort(({ data: a }, { data: b }) => b.pubDate - a.pubDate);
orchid shell
#

This will give the exact datetime of runtime when a post has missing date.

sharp axle
#

if pubDate is missing, previous algorithm would resolve as new Date(undefined) which is an invalid date and would break the sorting

#

best would be not to set default and force error from content schema, but it's also kinda annoying bc when you just start creating a content file, the schema gets evaluated as soon as you create the file. so having default would prevent an early round of error