Skip to main content

Interface: GenericDatabaseWriter<DataModel>

server.GenericDatabaseWriter

An interface to read from and write to the database within Convex mutation functions.

Available as ctx.db in mutations. You should generally use the DatabaseWriter type from "./_generated/server".

Extends GenericDatabaseReader with write operations. All reads and writes within a single mutation are executed atomically, you never have to worry about partial writes leaving your data in an inconsistent state.

Example

// Insert a new document:
const userId = await ctx.db.insert("users", { name: "Alice", email: "alice@example.com" });

// Update specific fields (shallow merge):
await ctx.db.patch("users", userId, { name: "Alice Smith" });

// Replace entire document (all non-system fields):
await ctx.db.replace("users", userId, { name: "Bob", email: "bob@example.com" });

// Delete a document:
await ctx.db.delete("users", userId);

// Delete multiple documents (collect first, then delete each):
const oldTasks = await ctx.db
.query("tasks")
.withIndex("by_completed", (q) => q.eq("completed", true))
.collect();
for (const task of oldTasks) {
await ctx.db.delete("tasks", task._id);
}

See

https://docs.convex.dev/database/writing-data

Type parameters

NameType
DataModelextends GenericDataModel

Hierarchy

Properties

system

system: BaseDatabaseReader<SystemDataModel>

An interface to read from the system tables within Convex query functions.

System tables include _storage (file metadata) and _scheduled_functions (scheduled function state). Use ctx.db.system.get() and ctx.db.system.query() just like regular tables.

Example

// Get file metadata from the _storage system table:
const metadata = await ctx.db.system.get("_storage", storageId);
// metadata has: _id, _creationTime, contentType, sha256, size

Inherited from

GenericDatabaseReader.system

Defined in

server/database.ts:152

Methods

get

get<TableName>(table, id): Promise<null | DocumentByName<DataModel, TableName>>

Fetch a single document from the database by its GenericId.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableTableNameThe name of the table to fetch the document from.
idGenericId<NonUnion<TableName>>The GenericId of the document to fetch from the database.

Returns

Promise<null | DocumentByName<DataModel, TableName>>

Inherited from

GenericDatabaseReader.get

Defined in

server/database.ts:23

get<TableName>(id): Promise<null | DocumentByName<DataModel, TableName>>

Fetch a single document from the database by its GenericId.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
idGenericId<TableName>The GenericId of the document to fetch from the database.

Returns

Promise<null | DocumentByName<DataModel, TableName>>

Inherited from

GenericDatabaseReader.get

Defined in

server/database.ts:34


query

query<TableName>(tableName): QueryInitializer<NamedTableInfo<DataModel, TableName>>

Begin a query for the given table name.

Queries don't execute immediately, so calling this method and extending its query are free until the results are actually used.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableNameTableNameThe name of the table to query.

Returns

QueryInitializer<NamedTableInfo<DataModel, TableName>>

Inherited from

GenericDatabaseReader.query

Defined in

server/database.ts:47


normalizeId

normalizeId<TableName>(tableName, id): null | GenericId<TableName>

Returns the string ID format for the ID in a given table, or null if the ID is from a different table or is not a valid ID.

This accepts the string ID format as well as the .toString() representation of the legacy class-based ID format.

This does not guarantee that the ID exists (i.e. db.get(id) may return null).

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableNameTableNameThe name of the table.
idstringThe ID string.

Returns

null | GenericId<TableName>

Inherited from

GenericDatabaseReader.normalizeId

Defined in

server/database.ts:63


insert

insert<TableName>(table, value): Promise<GenericId<TableName>>

Insert a new document into a table.

Example

const taskId = await ctx.db.insert("tasks", {
text: "Buy groceries",
completed: false,
});

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableTableNameThe name of the table to insert a new document into.
valueWithoutSystemFields<DocumentByName<DataModel, TableName>>The document to insert. System fields (_id, _creationTime) are added automatically and should not be included.

Returns

Promise<GenericId<TableName>>

The GenericId of the new document.

Defined in

server/database.ts:228


patch

patch<TableName>(table, id, value): Promise<void>

Patch an existing document, shallow merging it with the given partial document.

New fields are added. Existing fields are overwritten. Fields set to undefined are removed. Fields not specified in the patch are left unchanged.

This method will throw if the document does not exist.

Example

// Update only the "completed" field, leaving other fields unchanged:
await ctx.db.patch("tasks", taskId, { completed: true });

// Remove an optional field by setting it to undefined:
await ctx.db.patch("tasks", taskId, { assignee: undefined });

Tip: Use patch for partial updates. Use replace when you want to overwrite the entire document.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableTableNameThe name of the table the document is in.
idGenericId<NonUnion<TableName>>The GenericId of the document to patch.
valuePatchValue<DocumentByName<DataModel, TableName>>The partial document to merge into the existing document.

Returns

Promise<void>

Defined in

server/database.ts:259

patch<TableName>(id, value): Promise<void>

Patch an existing document, shallow merging it with the given partial document.

New fields are added. Existing fields are overwritten. Fields set to undefined are removed. Fields not specified in the patch are left unchanged.

This method will throw if the document does not exist.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
idGenericId<TableName>The GenericId of the document to patch.
valuePatchValue<DocumentByName<DataModel, TableName>>The partial document to merge into the existing document.

Returns

Promise<void>

Defined in

server/database.ts:278


replace

replace<TableName>(table, id, value): Promise<void>

Replace the value of an existing document, overwriting its old value completely.

Unlike patch, which does a shallow merge, replace overwrites the entire document. Any fields not included in the new value will be removed (except system fields _id and _creationTime).

This method will throw if the document does not exist.

Example

// Replace the entire document:
await ctx.db.replace("users", userId, {
name: "New Name",
email: "new@example.com",
});

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableTableNameThe name of the table the document is in.
idGenericId<NonUnion<TableName>>The GenericId of the document to replace.
valueWithOptionalSystemFields<DocumentByName<DataModel, TableName>>The new document. System fields can be omitted.

Returns

Promise<void>

Defined in

server/database.ts:306

replace<TableName>(id, value): Promise<void>

Replace the value of an existing document, overwriting its old value completely.

Unlike patch, which does a shallow merge, replace overwrites the entire document.

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
idGenericId<TableName>The GenericId of the document to replace.
valueWithOptionalSystemFields<DocumentByName<DataModel, TableName>>The new document. System fields can be omitted.

Returns

Promise<void>

Defined in

server/database.ts:322


delete

delete<TableName>(table, id): Promise<void>

Delete an existing document.

Example

await ctx.db.delete("tasks", taskId);

Type parameters

NameType
TableNameextends string

Parameters

NameTypeDescription
tableTableNameThe name of the table the document is in.
idGenericId<NonUnion<TableName>>The GenericId of the document to remove.

Returns

Promise<void>

Defined in

server/database.ts:338

delete(id): Promise<void>

Delete an existing document.

Note: Convex queries do not support .delete() directly on query results. To delete multiple documents, .collect() them first, then delete each one individually.

Parameters

NameTypeDescription
idGenericId<TableNamesInDataModel<DataModel>>The GenericId of the document to remove.

Returns

Promise<void>

Defined in

server/database.ts:352