0

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:

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.

SRel
  • 383
  • 1
  • 11
  • It would be helpful if we could see the actual document you're working with, before and after. You said "My attributes is an array" but it looks like a string in your log. – Doug Stevenson Mar 05 '23 at 18:30
  • I added a snippet of the document to the original post. The array currently contains just one element – SRel Mar 05 '23 at 18:36

2 Answers2

2

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

Saeed isa
  • 330
  • 3
  • 18
1

In JavaScript, == and !== do not compare the entire contents of an array. Comparing two arrays like that will always show that they are different.

What you will want to do instead is read up on how to correctly compare arrays in JavaScript considering each and every element in the array:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441