I am testing cloud functions in the firebase emulator and getting an error when trying to increment a field in the cloud firestore. Please check my code & error message below. Thanks for any help!
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();
export const newUserIncrementStat = functions.firestore.document("users/{uid}").onCreate((snap, context) => {
const docRef = db.doc("stats/users");
try {
return docRef.set({
totalUsers: admin.firestore.FieldValue.increment(1),
}, {merge: true});
} catch (e) {
console.log("Something is wrong: ", e);
return Promise.reject(e);
}
});
Error Message from Firebase Logs:
TypeError: Cannot read properties of undefined (reading ‘increment’)
Dependencies
firebase-admin: "^11.0.0"
firebase-functions: "^3.22.0"
firebase: 11.3.0
3
Answers
as @Min commented the error was with the firebase emulator, deploying the function directly to google cloud works without any error.
It seems like you’re not correctly setting a reference to your document.
Try
const docRef = db.collection("stat").doc("users")
.Instead of using set and giving it
merge:true
option you can just use update like this:This will increment totalUser count by 1 even if there was no field name totalUsers before.
It`s a issue with modularity improvement of firebase-admin. You can I rolled back to firebase-admin v10.3.0 or use modular import
import { FieldValue } from 'firebase-admin/firestore';
Or you can fully convert to modular import: