0
0
Firebasecloud~30 mins

Firestore trigger functions in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Firestore Trigger Functions
📖 Scenario: You are building a simple Firebase backend that reacts to changes in a Firestore database. You want to create functions that automatically run when documents are created or updated in a specific collection.
🎯 Goal: Build Firestore trigger functions that run when a document is created and when a document is updated in the users collection.
📋 What You'll Learn
Create a Firestore trigger function for document creation in the users collection.
Create a Firestore trigger function for document updates in the users collection.
Log a message inside each trigger function indicating the event type and document ID.
💡 Why This Matters
🌍 Real World
Automatically respond to database changes, such as sending notifications or updating related data.
💼 Career
Understanding Firestore triggers is essential for backend development with Firebase and building reactive cloud applications.
Progress0 / 4 steps
1
Set up Firebase Functions and import Firestore
Write the code to import functions from firebase-functions and initialize Firestore by importing admin from firebase-admin and calling admin.initializeApp().
Firebase
Need a hint?

Use require to import modules and call admin.initializeApp() to start Firebase Admin SDK.

2
Create a Firestore trigger for document creation
Create a Firestore trigger function called onUserCreate that runs when a document is created in the users collection. Use functions.firestore.document('users/{userId}').onCreate and log the message 'User created:' followed by the userId parameter.
Firebase
Need a hint?

Use context.params.userId to get the document ID from the path.

3
Create a Firestore trigger for document updates
Create a Firestore trigger function called onUserUpdate that runs when a document is updated in the users collection. Use functions.firestore.document('users/{userId}').onUpdate and log the message 'User updated:' followed by the userId parameter.
Firebase
Need a hint?

Use onUpdate and context.params.userId to get the document ID.

4
Export both trigger functions
Ensure both onUserCreate and onUserUpdate functions are exported from the module so Firebase can deploy them.
Firebase
Need a hint?

Make sure both functions are assigned to exports so Firebase can find them.