AndersR
AndersR2y ago

Examples of many to many relationship?

I am testing out Convex by building a notes app, in which notes and topics have a M:M relationship. Are there good examples or suggested best practices for implementing this? The only thing I've seen is the convex demos example - https://github.com/get-convex/convex-demos/tree/main/relational-data-modeling, which is quite basic. I also looked in the docs but didn't see anything. Here are a couple examples of what I'd be interested in seeing examples of: - Create a topic and associate with a note. - Query a note and get associated topics. (several more but just focusing on those for now) Here is my current schema:
export default defineSchema({
notes: defineTable({
content: v.optional(v.string()),
ownerId: v.string(),
title: v.string(),
topics: v.array(v.id("topics")),
}),
topics: defineTable({
ownerId: v.string(),
title: v.string(),
}),
});
export default defineSchema({
notes: defineTable({
content: v.optional(v.string()),
ownerId: v.string(),
title: v.string(),
topics: v.array(v.id("topics")),
}),
topics: defineTable({
ownerId: v.string(),
title: v.string(),
}),
});
Is using an array of topic ids the correct way to go to make the association? When querying a note, how would I then collect and return the topics? I tried looping through each topic in the topic array and then doing a get on each topic but that did not work. Any tips or insights would be appreciated! Thanks!
5 Replies
AndersR
AndersROP2y ago
To be clear, that schema only represents a 1:M relationship. Want to get that working first, but the goal is a M:M. And to sort of rubber duck this a bit, one thought I had was to create a noteTopics join table. However, I think I am too locked in on a relational paradigm. The document db model is not something I have a lot of experience with.
jamwt
jamwt2y ago
Functional Relationships: Helpers
In this post, we’ll look at some helper functions to help write code to traverse relationships in a readable, predictable, and debuggable way.
jamwt
jamwt2y ago
Relationship Structures: Let's Talk About Schemas
In this post we’ll look at some patterns for structuring relationships in the Convex database.
AndersR
AndersROP2y ago
@jamwt perfect, thx, will take a look.
jamwt
jamwt2y ago
convex is document-relational, so your existing ideas about relational modeling (such as using join tables) work just fine! those posts will go into some details about this

Did you find this page helpful?