Skip to content

3. Validation ​

The schema of step 2 already gives you the types. Add validation: 'error' so the server also refuses documents that do not fit:

ts
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 }],
})
validationA write through the APIThe MongoDB validator
'off'not checkednot touched
'warn'checked; an invalid document is stored and loggedlogs
'error' (default)refused with 400refuses

Existing collections

'error' is the default since 3.0. When you declare a collection that other writers already filled, start with 'warn': the start logs how many stored documents do not match, and nothing is refused until you switch.

The server turns the schema into a $jsonSchema validator of the collection, so the shell and other services are checked too. Partial updates ($set) are checked by that validator, whole documents by the schema itself.

Show the errors in a form ​

A refused write throws a MongocampRequestError. Its issues name the fields:

vue
const draft = reactive({ name: '', email: '' })
const issues = ref<Array<{ path: string, message: string }>>([])
const message = ref('')

async function add() {
  issues.value = []
  message.value = ''
  try {
    await customers.insert({ ...draft })
    draft.name = ''
    draft.email = ''
    await refresh()
  }
  catch (error) {
    // 400: the fields of the schema that do not fit; 409: a unique index (the email is taken)
    const failure = error as MongocampRequestError
    issues.value = failure.issues ?? []
    message.value = failure.message
  }
}
vue
<form @submit.prevent="add">
  <input
    v-model="draft.name"
    placeholder="name"
  >
  <input
    v-model="draft.email"
    placeholder="email"
  >
  <button>Add</button>
  <p
    v-if="message"
    class="error"
  >
    {{ message }}
  </p>
  <ul class="issues">
    <li
      v-for="issue in issues"
      :key="issue.path"
    >
      {{ issue.path }}: {{ issue.message }}
    </li>
  </ul>
</form>

Inserting { name: '', email: 'not an email' } answers 400 with two issues:

json
{
  "code": 4010,
  "msg": "the document does not match the schema of the collection customers",
  "additionalInfo": "",
  "issues": [
    { "path": "name", "message": "Too small: expected string to have >=1 characters" },
    { "path": "email", "message": "Invalid email address" }
  ]
}

The messages come from your schema library. Change them there (z.string().min(1, 'a name, please')). See Errors for the shape of every error.

Released under the MIT License.