Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Firebase function onUpdate of document field value

I am looking for a solution to making the below code trigger onUpdate of a field value, rather than by the entire document.

Is it possible using the firebase-functions package to listen to a field value, let's say a field with a time stamp called lastUpdate? Alternatively, I am leaning toward a HTTP trigger called via onClick using axios but cannot find any resources, documentation or tutorials that help my understanding. If you know of any, I'd love to read them.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const sgMail = require('@sendgrid/mail');

try {
  admin.initializeApp();
} catch (e) {
  console.log(e);
}

var SENDGRID_API_KEY = functions.config().sendgrid.key;
sgMail.setApiKey(SENDGRID_API_KEY);

exports = module.exports = functions.firestore
  .document('users/{id}')
  .onUpdate(snap => {
    const user = snap.data();
    const msg = {
      to: user.email,
      from: '[email protected]',
      templateId: 'd-6c0e0385808c480ab475748a6eeed773',
      dynamic_template_data: {
        firstName: user.firstName,
        email: user.email,
        id: user.id
      }
    };
    return sgMail.send(msg).catch(err => console.log(`${user.email} - ${err}`));
  });
like image 249
Darren Avatar asked Jun 14 '26 11:06

Darren


1 Answers

Cloud Firestore triggers Cloud Functions on a document level. There is no option to trigger a function only when a specific field in the document is changed. If you want that level of granularity for your triggers, consider using the realtime database.

like image 59
Frank van Puffelen Avatar answered Jun 16 '26 10:06

Frank van Puffelen