Querying
Any component or page of your application can fetch content from the content/ directory.
The queryContent()
function is auto-imported by Nuxt Content to build queries with a MongoDB-like syntax.
Usage
Create a query builder
Create a new query builder with queryContent()
.
You can give a path as a parameter, starting at the root of your content/
directory.
queryContent('/')
Resolve the query
Resolve the query with one of these methods:
find()
will always return an array of one or more items corresponding to documents in thecontent/
directory.
/* returns every document found at the root (/) path of the content/ directory */queryContent('/').find()
findOne()
will return an object corresponding to the matching document.
/* returns only the matching index.md found at the root (/) path of the content/ directory */queryContent('/').findOne()
Wrap your query with useAsyncData
To prevent fetching duplication on first load, wrap your query in the useAsyncData
composable (auto-imported as well).
const { data } = await useAsyncData('home', () => queryContent('/').findOne())
<script setup>const { data } = await useAsyncData('home', () => queryContent('/').findOne())</script><template><main> <pre> {{ data }} </pre></main></template>
Query builder
queryContent()
supports methods chaining to create advanced queries.
Once your query is ready, make sure to end your call with .find()
, .findOne()
or .findSurround()
to effectively trigger data fetching.
Example
This example uses the where()
and only()
methods to fetch the title of the document corresponding to the current browser URL.
<script setup>const { path } = useRoute()const { data } = await useAsyncData(`content-${path}`, () => { return queryContent().where({ _path: path }).only(['title']).findOne()})</script><template> <main> <h1>{{ data.title }}</h1> </main></template>
API routes
Nuxt Content creates a REST GET
endpoint for each document in the content/
directory.
The API root path /api/_content/query
accepts query parameters such as:
/api/_content/query?only=title
/api/_content/query?sort=size:1
/api/_content/query?without=body
/api/_content/query?_params={"where":{"_path":"/hello"},"without":["body"]}
Example
# Hello Content v2!