Skip to content

7. Relations ​

An order refers to its customer by _id. refs names the collection of that field:

ts
import { ObjectId } from 'mongodb'
import { z } from 'zod'

export default defineMongocampCollection({
  name: 'orders',
  schema: z.object({
    customerId: z.instanceof(ObjectId),
    items: z.array(z.object({
      product: z.string().min(1),
      qty: z.int().min(1),
      price: z.number().min(0),
    })).min(1),
    // computed by a before-hook (step 5)
    total: z.number().min(0).optional(),
    status: z.enum(['open', 'paid', 'shipped']).default('open'),
  }),
  validation: 'error',
  // step 4: behaviours
  timestamps: { createdBy: true }, // createdAt, updatedAt and the user who created the order
  owner: true, // the owner is createdBy: every user sees and changes only the own orders
  softDelete: true, // a delete sets deletedAt, restore brings the order back
  versioned: true, // _v: a write based on an outdated order answers 409
  audit: true, // the history of every order
  protectedFields: ['total'], // clients cannot write it, the before-hook does
  // step 6: the lists the app shows
  indexes: ['status', ['customerId', '-createdAt']],
  // step 7: customerId refers to a customer
  refs: { customerId: 'customers' },
})

A read with expand replaces the id by the document. In the order list:

vue
// the orders of the user (owner), with the customer of each order (expand), updated when they change
const orders = useMongocampCollection('orders')
const live = useMongocampLive('orders', { expand: ['customerId'] })
vue
<table>
  <tr
    v-for="order in live.documents.value"
    :key="documentId(order)"
  >
    <td>{{ order.customerId?.name ?? 'unknown customer' }}</td>
    <td>{{ order.items.length }} items</td>
    <td>{{ order.total }}</td>
    <td>{{ order.status }}</td>
    <td>{{ order.createdAt.toLocaleString() }}</td>
    <td>
      <button @click="markPaid(order)">
        Paid
      </button>
      <button @click="remove(order)">
        Delete
      </button>
      <button @click="showHistory(order)">
        History
      </button>
    </td>
  </tr>
</table>

order.customerId is typed as the customer document, or null. expand only accepts the declared references, so a typo is a type error.

The rules:

  • Never more than a direct read: the customer is read with the reader's grants and the read scope of the customers collection (owner, soft delete, your read hooks). A customer the reader cannot read is null, not an error.
  • Cost: one query per expanded field and page (all ids at once), not one per order.
  • Writing back: update(order, { status: 'paid' }) with an expanded order sends only status. The composable turns expanded references back into ids where it sends them.
  • One level only: no expansion inside the customer. Reverse lookups ("the orders of a customer") are a find with a filter on customerId.

On the REST API: GET /api/mongocamp-server/mongodb/collections/orders/documents?expand=customerId.

Released under the MIT License.