0
votes

Can anyone please give me pointers for getting Firestore working with Cloud Functions.

I am trying to follow the documentation here: https://firebase.google.com/docs/firestore/extend-with-functions

Using firebase deploy --only functions:_onFirestoreWrite_notifications

I get the message: HTTP Error: 400, The request has errors

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

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();

admin.initializeApp();

const db = admin.firestore();

exports._onFirestoreWrite_notifications = functions.firestore
  .document('_notifications')
  .onWrite((change, context) => {

  //..

  });
1
Where is your problem? From my point of view, next step would be deployment, see firebase.google.com/docs/functions/…Markus Schulte
Firebase deploy errors so I guess I am missing somthing before "exports." that allows Firestore to runPHILL BOOTH
Please update your question with the command you are running and the corresponding error message from "firebase deploy ..."Markus Schulte

1 Answers

1
votes

Update following OP's comment below: apparently using underscores in the Cloud Function name is causing an issue.

With the onWrite() trigger you are going to trigger an event for any change to a specific document. Documents in Firestore are stored within collections, therefore you need to pass the full path of the document to the document() method, as follows:

exports.onFirestoreWriteNotifications = functions.firestore
  .document('collection/_notifications')  //Note the addition of the collection
  .onWrite()

In addition, note that you don't need to do

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();

since, in your Cloud Functions, you will use the Admin SDK for Node.js to interact with Firestore.

So doing

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

is sufficient as explained here and here (Node.js tab).

Then you will call the Firestore database with admin.firestore(), like for example, admin.firestore().collection('_hello').add({...})


In addition, note that you have to return the Promises returned by the asynchronous tasks.

If I refer to your initial code (before your edit)

exports._onFirestoreWrite_notifications = functions.firestore
  .document('collection/_notifications')
  .onWrite((change, context) => {

    db.firestore//.collection('_hello').add({
      text: "itworks",
      from: "onWrite"
    });

  });

you need to do

return admin.firestore().collection('_hello').add({
  text: "itworks",
  from: "onWrite"
});
//!!! Note the return (and the use of admin.firestore() )

This is an important point and is very well explained in the three videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/