Skip to content

Server - Documents

Functions for handling single Firestore documents on the server.

Reading Documents

ts
import { getDocument } from "@typed-firestore/server";

/** Get a document — result is typed as FsMutableDocument<User> */
const user = await getDocument(refs.users, "id123");

/** The returned document has a typed update function */
await user.update({
  is_active: true,
  modified_at: FieldValue.serverTimestamp(),
});

Transactions

All document operations have transaction variants (suffixed with Tx). In a transaction, the update function is synchronous and executes when the transaction is committed.

ts
await runTransaction(async (tx) => {
  const user = await getDocumentTx(tx, refs.users, "id123");

  /** Synchronous — executes on commit */
  user.update({
    is_active: true,
    modified_at: FieldValue.serverTimestamp(),
  });
});

Documents That Might Not Exist

Use getDocumentMaybe when a document might not exist. It returns null instead of throwing.

ts
const user = await getDocumentMaybe(refs.users, "id123");
if (user) {
  console.log(user.data.displayName);
}

Writing Documents

ts
import {
  setDocument,
  updateDocument,
  deleteDocument,
  addDocument,
} from "@typed-firestore/server";

/** Create or overwrite */
await setDocument(refs.users, "id123", {
  displayName: "Alice",
  is_active: true,
});

/** Update specific fields */
await updateDocument(refs.users, "id123", {
  is_active: false,
});

/** Add with auto-generated ID */
await addDocument(refs.users, {
  displayName: "Bob",
  is_active: true,
});

/** Delete */
await deleteDocument(refs.users, "id123");

API Reference

Single Documents

FunctionDescription
getDocumentFetch a document
getDocumentMaybeFetch a document that might not exist
getDocumentTxFetch a document as part of a transaction
getDocumentMaybeTxFetch a document that might not exist as part of a transaction
getSpecificDocumentFetch a document from an inconsistent collection
getSpecificDocumentTxFetch a document from an inconsistent collection as part of a transaction
addDocumentAdd a document with an auto-generated ID
addDocumentTxAdd a document with an auto-generated ID as part of a transaction
setDocumentCreate or overwrite a document
setDocumentTxCreate or overwrite a document as part of a transaction
setSpecificDocumentCreate or overwrite a specific document
setSpecificDocumentTxCreate or overwrite a specific document as part of a transaction
updateDocumentUpdate a document
updateDocumentTxUpdate a document as part of a transaction
updateDocumentWithPartialUpdate a document with a partial object
updateDocumentPartialTxUpdate a document with a partial object as part of a transaction
deleteDocumentDelete a document

Released under the Apache-2.0 License.