Skip to content

Firestore data aggregation of documents

I’m creating an expense tracker app, where the user can set a monthly budget (ie. $3,000) and a field ‘total spending for the month’ would update each time a user adds an expense. How would I do this using Firestore Database? So far, I have the expense record stored in a subcollection inside a document (using user-id) inside a user’s collection.

  expenseForm.addEventListener('submit', e => {
    e.preventDefault();
    db.collection('users').doc(user.uid).collection('expense-record').doc().set({
      title: expenseTitle.value,
      amount: expenseAmount.value,
      category: expenseCategory.value,
      date: expenseDate.value,
    });
  });

Answer

Oooh, that’s a fun use-case.

If you want to prevent the user from ever spending more than their budget, I’d:

  1. Store the budget somewhere in the database.
  2. Store the aggregate spending for the current month too, and use security rules to ensure that every expense record added/deleted also updates the aggregate spending for the month.
  3. Use security rules to reject spend records that would push the aggregate over their budget.

These are non-trivial, but they would allow you to have a purely client-side solution. I imagine others may answer with solutions like Cloud Functions, which are totally valid too.