· Designer & No-Code Builder

Average Aggregation Query not working in Cloud Function

I was able to get the count() aggregation working via cloud functions, but am getting an error "ReferenceError: AggregateField is not defined" when I try to get the average of a field. I've copied the code directly from the firestore docs (https://firebase.google.com/docs/firestore/query-data/aggregation-queries#node.js)

Has anybody been able to get average or sum to work in a cloud function?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code

exports.getFlushAvgDryWeight = functions.
	runWith({
		timeoutSeconds: 10
  }).https.onCall(
  async (data, context) => {
  		if (!context.auth.uid) {
      return;
    }
    const team = data.team;

  try {
    const firestore = admin.firestore();
    const coll = firestore.collection('flushes');
    const q = coll.where("team", "==", team);
    const averageAggregateQuery = q.aggregate({
        averageDryWeight: AggregateField.average('dryWeight'),
      });

    const snapshot = await averageAggregateQuery.get();
    return snapshot.data().averageDryWeight;
      
  } catch (error) {
    console.error('Error counting documents:', error);
    throw new functions.https.HttpsError("unknown", "custom-identifier", error);
  }

  }
);

2
3 replies