6. Indexes
Declare the indexes with the collection. The server creates them at the start and keeps them in line with the declaration.
One customer per email address:
import { z } from 'zod'
export default defineMongocampCollection({
name: 'customers',
schema: z.object({
name: z.string().min(1),
email: z.email(),
}),
// step 3: refuse invalid documents (the default `'warn'` stores them and logs a warning)
validation: 'error',
// step 4: createdAt and updatedAt
timestamps: true,
// step 6: one customer per email address
indexes: [{ fields: { email: 1 }, unique: true }],
})The indexes of the order lists, by status and the newest orders of a customer:
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' },
})| Form | Index |
|---|---|
'status' | { status: 1 } |
'-createdAt' | { createdAt: -1 } |
['customerId', '-createdAt'] | { customerId: 1, createdAt: -1 } |
{ fields: { email: 1 }, unique: true } | with options: unique, sparse, expireAfterSeconds, partialFilterExpression, collation, name |
A second customer with the same email now answers 409 with code 11000. The form of step 3 shows the message.
The behaviours add the indexes they need by themselves:
ownerindexes the owner field, because every read of a user filters by it;- with
softDeletea unique index ignores deleted documents, so the email of a deleted customer can be used again.
The server manages only its own indexes (names starting with mongocamp_idx_): it creates them, rebuilds a changed one and drops one you removed from the declaration. Indexes made in the shell are left alone. A failure, such as duplicates for a new unique index, is logged and the server starts anyway.
Check that a list uses an index with explain in the shell:
db.orders.find({ createdBy: 'ann', deletedAt: null }).sort({ createdAt: -1 }).explain().queryPlanner.winningPlan