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:
Scenario1: attributes field changed
I changed an array element, the output then is:
Scenario2: attributes field unchanged
I changed any other field in the document, the output then is also:
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.