Defining mutations
mutation
Define a public mutation function that can be called from clients.Argument validation object using validators from
convex/values.Return value validator for type safety and validation.
internalMutation
Define an internal mutation that can only be called from other Convex functions.- Mutations called from actions or scheduled functions
- Administrative operations
- Mutations that should not be exposed to clients
Mutation context
MutationCtx
The context object passed to mutation handlers.Read-write database interface. Provides all read methods plus See Database API for complete details.
insert, patch, replace, and delete.Authentication interface to get the current user’s identity.
Call a query function within the same transaction.The query runs within the same transaction, seeing a consistent snapshot of the database.
Call a mutation function within the same transaction.The mutation runs in a sub-transaction. If it throws an error, all of its writes will be rolled back.
Database operations
Mutations have access to all database write operations:insert
Insert a new document into a table.patch
Shallow merge updates into an existing document.replace
Completely replace a document with new values.delete
Delete a document from the database.Transaction guarantees
Convex guarantees that all operations within a single mutation are:Atomic
All writes either succeed together or fail together. You never have to worry about partial writes leaving your data in an inconsistent state.
Isolated
Each mutation sees a consistent snapshot of the database. Concurrent mutations don’t interfere with each other.
Serializable
Mutations execute as if they ran one at a time in some order, even when running concurrently.
Best practices
Always validate arguments
For security, add argument validation to all public mutations in production apps.
Use internal mutations
For mutations called only from actions or scheduled functions, use
internalMutation to prevent direct client calls.Keep mutations focused
Each mutation should do one logical operation. Break complex operations into multiple mutations if needed.
Return useful values
Return the new document ID or other useful information for the client.