Firebase Admin Firestore Batched Writes

Apply multi-document Firestore mutations atomically with admin SDK batched writes, checking batch size limits and ordering dependencies.

TypescriptNodeData Integrity

Code

snippet
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?.();