Skip to content
This repository has been archived by the owner on Feb 27, 2022. It is now read-only.

Filtering documents by relationship #6

Closed
tyteen4a03 opened this issue Apr 9, 2021 · 5 comments
Closed

Filtering documents by relationship #6

tyteen4a03 opened this issue Apr 9, 2021 · 5 comments

Comments

@tyteen4a03
Copy link

I have two types of nodes: Post and Snippet. I would like a Post to be composed of multiple snippets (which Snippet it belongs to is defined in the Snipper's front matter), while retaining the ability to refer to a Snippet on its own.

Is it possible to call getAll*Nodes('snippet') from the Post document and only have it return the Snippets that belong to the post?

@shadcn
Copy link
Owner

shadcn commented Apr 10, 2021

Can you give an example of a post and snippet frontMatter so we can determine the relationship?

Thank you

@tyteen4a03
Copy link
Author

post.md:

---
title: Post
---

snippet.md:

---
title: Snippet
belongsToPost: post
---

@shadcn
Copy link
Owner

shadcn commented Apr 10, 2021

OK. Let me see. I'll try to put together a quick example.

@shadcn
Copy link
Owner

shadcn commented Apr 10, 2021

OK I created an example here:

Demo: https://next-mdx-post-snippet.vercel.app
Repo: https://github.com/arshad/next-mdx-post-snippet

Here are some key parts:

Define your MDX types

https://github.com/arshad/next-mdx-post-snippet/blob/25aed7eefcb2616fd7da311189eff2071fa6fa20/next-mdx.json#L1

{
  "post": {
    "contentPath": "content/posts",
    "basePath": "/blog"
  },
  "snippet": {
    "contentPath": "content/snippets"
  }
}

Set the post in the snippet

---
title: Hello World
post: <------- This must match the key we used above in next-mdx.json
  - first-post <-----------------
---

```jsx
export function HelloWorld() {
  return <p>Hello World</p>
}

Get the snippets for a post

export async function getStaticProps(context) {
  const post = await getMdxNode("post", context)

  if (!post) {
    return {
      notFound: true,
    }
  }

  const snippets = await getAllMdxNodes("snippet")

  return {
    props: {
      post,
      snippets: snippets.filter((snippet) =>
        snippet.relationships.post.some(({ slug }) => slug === post.slug)
      ),
    },
  }
}

https://github.com/arshad/next-mdx-post-snippet/blob/25aed7eefcb2616fd7da311189eff2071fa6fa20/pages/blog/%5B...slug%5D.tsx#L46

Hope this helps

@tyteen4a03
Copy link
Author

OK so as I suspected I would need to do the filtering myself. Thanks either way :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants