Home > Software design >  Problem getting value of Firestore document in Cloud Functions
Problem getting value of Firestore document in Cloud Functions

Time:08-06

I am writing a Firebase cloud function to generate a restricted API key from Algolia whenever a document from the Users collection change.

The Algolia part works fine, but I do not get the userid value from the related Firestore document.

When I run this code, the first console.log throws the following error: TypeError: change.data is not a function.

I have checked the Firestore document field name and path.


const functions = require("firebase-functions");
const admin = require('firebase-admin');

admin.initializeApp();

  //Generate a new API key when a user document is changed. (This will later be changed to trigger when a user document is created in Firestore)
   exports.generateAlgoliaAPIKey = functions.firestore
    .document('users/{user}')
    .onWrite((change, context) => {

      const userid = change.data().userid

      console.log(userid)

      const publicKey = client.generateSecuredApiKey(
        'XXXXXXXXXXXXXXXX', // A search key that you keep private
        {
          filters: `owninguser:${userid}`
        }
      );

      console.log("this is the new key: "   publicKey)


    });

CodePudding user response:

You can access the new data with: change.after.data() or previous data with: change.before.data().

Check the documentation for trigger functions here.

  • Related