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/