Firestore Cloud Function判断数组字段变化失效问题排查
问题原因
你用!==直接比较两个数组,在JavaScript里数组属于引用类型,!==对比的是两个变量的内存引用地址,而非数组的实际内容。Firestore每次返回的data()都是新的对象实例,所以哪怕attributes数组内容完全没变,previousAttributes和newAttributes也是两个不同的引用,newAttributes !== previousAttributes永远为true,导致不管其他字段怎么改,都会进入if分支。
解决方案
需要对比数组的实际内容是否一致,以下是两种可行方案:
方案1:JSON字符串转换对比(适合简单元素数组)
把数组转成JSON字符串后再比较,这种方法简单高效,适合数组元素为字符串、数字、布尔等简单类型的场景:
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}`); // 转成JSON字符串后对比内容 if (JSON.stringify(newAttributes) !== JSON.stringify(previousAttributes)) { console.log("Important Change happened"); return console.log("Update successfull important change"); } else { console.log("Unimportant Change happened"); return console.log("Update successfull unimportant change"); } });
这里加了?.和|| []是为了处理字段不存在的情况,避免报错。
方案2:手动遍历对比(适合复杂元素数组)
如果数组里包含对象等复杂类型,JSON.stringify可能因为对象属性顺序问题导致误判,这时可以手动遍历数组逐个对比:
// 辅助函数:对比两个数组内容是否一致 function arraysAreEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false; for (let i = 0; i < arr1.length; i++) { // 如果是对象,需要递归对比,这里示例假设元素是简单类型或可直接比较的对象 if (JSON.stringify(arr1[i]) !== JSON.stringify(arr2[i])) { return false; } } return true; } 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 (!arraysAreEqual(newAttributes, previousAttributes)) { console.log("Important Change happened"); return console.log("Update successfull important change"); } else { console.log("Unimportant Change happened"); return console.log("Update successfull unimportant change"); } });
内容的提问来源于stack exchange,提问作者SRel
相关产品推荐
相关产品推荐

