Relations
Documents can point to other documents: a post has an author, a product has tags. A read can load the related documents in the same call.
A relation field stores the ids. A join lists the documents that point back. This page covers how reads load related documents and what happens when one is deleted.
Populate
By default, a read loads related documents two levels deep. populate picks what to load:
// Every relation, two levels deep (the default)
await cms.find("posts");
// Ids only
await cms.find("posts", { populate: false });
// Only these paths
await cms.find("posts", { populate: { author: { avatar: true }, tags: true } });
// A join loads only when you name it
await cms.find("authors", { populate: { posts: true } });
trueon a key loads one level. A nested object goes further.depthsets how farpopulate: truegoes:cms.find("posts", { depth: 1 }).- A related document that no longer exists reads as
null. Amanylist leaves it out. - The result types follow
populate. Withpopulate: false,post.authoris astring. createandupdatereturn ids, not loaded documents.
Over HTTP, the same options are query parameters: ?populate=author.avatar,tags or ?populate=false. HTTP reads stop at 5 levels.
Keep related documents small
A loaded document has all its fields. When a page only needs a few, set select on the relation field:
author: {
type: "relation",
collection: "authors",
select: { name: true, avatar: true },
},
Every read that loads author now returns { id, name, avatar }. A read that selects inside the relation picks other fields instead:
await cms.find("posts", { select: { title: true, author: { bio: true } } });
See Reading for select and filters.
When a document is deleted
When you delete a document, every relation that points to it applies its onDelete rule:
onDelete | What happens | Default for |
|---|---|---|
set-null | A single relation becomes null. A many list drops the id. | Optional relations |
restrict | The delete fails with a 409 and lists the documents that point to it. | required relations, image, file |
cascade | The documents that point to it are deleted too. |
// Delete the comments of a deleted post
post: { type: "relation", collection: "posts", required: true, onDelete: "cascade" },
- Everything happens in one transaction, with the hooks of every changed document.
- In server code, a failed
restrictthrows aConflictErrorfromtenoncms. - A
requiredrelation cannot useset-null. A global cannot usecascade.