skip to Main Content

I am building a Firebase project where I need to run a cloud function whenever a document is created in a specific Firestore collection. I’m using Node.js with the Firebase Admin SDK and have set up Firebase functions. Everything else is working correctly, but I can’t get the function to trigger upon document creation at a specific Firestore path

Here’s my code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccount.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

exports.testFunction = functions.firestore
    .onDocumentWritten("Test/{docId}", (change, context) => {
        /* ... */
        console.log('Written to Test');
    });

When I add a new document to the Test collection, the testFunction does not get triggered as expected. I intended for this function to execute and log "Written to Test" each time a document is created in this path.

Could anyone help me understand why this trigger isn’t firing and suggest how I might fix this?

2

Answers


  1. From the Firebase documentation on using console.log in Cloud Functions:

    The recommended solution for logging from a function is to use the logger SDK for your platform. With Node.js, you can instead use standard JavaScript logging calls such as console.log and console.error, but you first need to require a special module to patch the standard methods to work correctly:

    require("firebase-functions/logger/compat");

    Once you have required the logger compatibility module, you can use console.log() methods as normal in your code:

    exports.helloError = functions.https.onRequest((request, response) => {
      console.log('I am a log entry!');
      response.send('Hello World...');
    });
    
    Login or Signup to reply.
  2. You said in the comments that you’re running the code you shared as a plain Node.js script, which won’t work. Node.js looks for top-level code to execute, so it just runs the admin.initializeApp({...}) and then does nothing else.

    To get the onDocumentWritten to execute and respond to changes in Firestore,, you need to run it in an environment that can execute the Cloud Function. So this can either be the production Cloud Functions environment on Google Cloud or the Firebase emulator for Cloud Functions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search