I need to detect when only a certain field has changed in my cloud function

Viewed 2139

Check out my cloud functions below. I want to do some things when only the status field in Job/{jobId} changes and then some other things whenany other fields in Job/{jobId} changes, so I created both functions below. But it seems that both functions fires when the status field changes. How can I restrict this behaviour.

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

//-----
const db = functions.database;
const adminDb = admin.database();
//-----


//JOBS
exports.onJob = db
    .ref("/Jobs/{jobId}")
    .onWrite((event) => {

        //...my codes

    });



exports.onJobStatus = db
    .ref("/Jobs/{jobId}/status")
    .onWrite((event) => {

   //...my codes

    });
3 Answers

Posting as an answer because I'll likely look this up again in the future.

The correct syntax as of 2021 is to use snap.before:

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

functions.firestore.document('foo/{id}').onChange((snap, context)) => {
  if(snap.before.data().status !== snap.after.data().status){
    // ...
  }
}
Related