Firebase Admin Firestore Batched Writes
Apply multi-document Firestore mutations atomically with admin SDK batched writes, checking batch size limits and ordering dependencies.
Code
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore, WriteBatch } from 'firebase-admin/firestore';
const app = initializeApp({
credential: cert(JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT ?? '{}')),
});
const db = getFirestore(app);
const MAX_BATCH = 450; // 官方上限 500,留出余量
async function importProducts(products) {
let batch: WriteBatch = db.batch();
let pending = 0;
for (const product of products) {
const ref = db.collection('products').doc(product.sku);
batch.set(ref, {
title: product.title,
price: product.price,
updatedAt: FieldValue.serverTimestamp(),
});
pending += 1;
if (pending >= MAX_BATCH) {
await batch.commit();
batch = db.batch();
pending = 0;
}
}
if (pending > 0) await batch.commit();
}
const products = Array.from({ length: 920 }, (_, i) => ({
sku: 'SKU-' + i,
title: 'Product ' + i,
price: (i % 50) * 3 + 5,
}));
await importProducts(products);
const snapshot = await db.collection('products').limit(3).get();
console.log('imported docs visible:', snapshot.size);
await app.delete?.();How it works
The code’s whole job belongs to the function importProducts.
Repetition is confined to for (const product of products) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import line is the dependency contract: initializeApp, cert, getFirestore, WriteBatch come from firebase-admin/app and nothing else.
Configuration comes from the environment — it reads FIREBASE_SERVICE_ACCOUNT, so the same code switches behavior between environments without edits.
What to watch for
- External dependency:
firebase-admin/appandfirebase-admin/firestore— install them before running the snippet.
Using it
The primary signature is async function importProducts(products)
Output lines are prefixed (imported docs visible:), making each step’s effect easy to spot.
Key statements
await app.delete?.();
const snapshot = await db.collection('products').limit(3).get();
const products = Array.from({ length: 920 }, (_, i) => ({
sku: 'SKU-' + i,
title: 'Product ' + i,
price: (i % 50) * 3 + 5,
}));
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- `firebase-admin/app` and `firebase-admin/firestore` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.