Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore Cloud Function check if a field changed fails

I want to trigger a cloud function only when a certain field of a document changed.
For this I wrote a simple if-statement checking the old field value against the new one. However, even if the field did not changed this if clause is returning true and I have no clue why this is.
My code snippet:

exports.keekzCardUpdated = functions.firestore
    .document("keekzs/{keekzsDocId}/keekzCards/{keekzCardDocId}")
    .onUpdate(async (change, context ) => {
      const previousData = change.before.data();
      const newData = change.after.data();
      const previousAttributes = previousData.attributes;
      const newAttributes = newData.attributes;
      console.log(`prev Attributes ${previousAttributes}`);
      console.log(`new Attributes ${newAttributes}`);

      if (newAttributes !== previousAttributes) {
        // Here would come the logic I want to execute
        console.log("Important Change happened");
        return console.log("Update successfull important change");
      } else {
        // Here the function should basically stop
        console.log("Unimportant Change happened");
        return console.log("Update successfull unimportant change");
      }
    });

My attributes is an array.

A snippet of the actual document:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Scenario1: attributes field changed

I changed an array element, the output then is:
enter image description here

Scenario2: attributes field unchanged

I changed any other field in the document, the output then is also:
enter image description here

As you see no matter what everytime the first if-clause is executed.
I also tried a flipping variable which is false at the beginning and then flips when the same if-clause is being evaluated. This flip was also executed everytime anything in the document changed however the previousAttributes and the newAttributes value was identical.

>Solution :

Javascripts arrays are objects, hence, they are not compared based on their values but based on the references of the variables

in your case it will always be not equal

quick solution could be:

previousAttributes.toString() !== newAttributes.toString()

It will convert the array to string and compare value to value

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading