Content Modeling

Relations

Link documents and load them together.

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 } });
  • true on a key loads one level. A nested object goes further.
  • depth sets how far populate: true goes: cms.find("posts", { depth: 1 }).
  • A related document that no longer exists reads as null. A many list leaves it out.
  • The result types follow populate. With populate: false, post.author is a string.
  • create and update return 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.

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:

onDeleteWhat happensDefault for
set-nullA single relation becomes null. A many list drops the id.Optional relations
restrictThe delete fails with a 409 and lists the documents that point to it.required relations, image, file
cascadeThe 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 restrict throws a ConflictError from tenoncms.
  • A required relation cannot use set-null. A global cannot use cascade.