Nuxt Content Queries

Nuxt Content 2 gives us an effortless way to query our content using the queryContent method:

// composables/useArticles.js
export default () =>
queryContent('articles')
.where({
// Optional fields that may be true or non-existent
ghost: { $ne: true },
newsletter: { $ne: true },
// Don't render articles scheduled for the future
date: { $lte: new Date() },
})
.only(['title', 'path', 'description', 'date', 'tags'])
.sort({ date: -1 })
.find();

Here, I’ve created a composable called useArticles for my blog, which grabs all of the content inside of the content/articles/ directory.

The queryContent composable is a query builder, which gives us a lot of expressiveness in what data we fetch. Let’s see how we’re using this here.

First, we’re using a where clause to filter out all the articles we don’t want. Sometimes I will add an article before I want it to be “published” to the site.

I do this by setting the date in the future and then only taking articles before “today” using this clause:

date: { $lte: new Date() }

Second, some articles are the newsletters I write each week. Others are pieces of content that I want to keep in the articles folder but don’t want to be published.

I use frontmatter fields to specify this:

---
newsletter: true # This is a newsletter
---
---
ghost: true # This content won't appear on the site
---

Third, we use the only clause to grab just the fields we need. By default, the queryContent method returns a lot of data, including the entire piece of content itself, so this can make a big difference in payload size.

Lastly, as you have probably guessed, we have a sort clause to sort the articles so the most recent ones appear last.

The queryContent composable has more options than this, which you can read about on the docs.