首页 > 解决方案 > 如何仅在使用 onUpdate 触发 Firestore 云功能更改字段时触发操作?

问题描述

我的事件文档中有一个名为的字段,title其中包含一个布尔值。我在我的文档中设置了 onUpdate firestore 触发器。我想如果我title的更新,那么我会采取一些行动。但如果其他字段被更新,那么我根本不会执行任何操作。怎么做 ?

如果每次文档有更新时都调用下面的函数,我没问题,但我只想在更新时做一些进一步的title操作

exports.dbEventsOnUpdate = functions.firestore
.document('events/{eventId}').onUpdate(async (change,context) => {

        try {        
            const eventID = context.params.eventId

            if (titleIsUpdated) {
               return db.doc(``).set(newData)
            } else {
               // do nothing here
               return null
            }

        } catch(error) {
            console.log(error)
            return null
        }

    })

标签: firebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


目前,Firestore Cloud Functions 无法基于字段更新触发。它仅在文档更新时触发。

您实际上可以使用以下代码检查标题是否已更新:

const newValue = change.after.data();
const previousValue = change.before.data();

const titleIsUpdated = newValue.title !== previousValue.title;

但请记住,当该文档中的字段发生更改时,您的函数将始终被触发。这可能会产生更多成本,因为 Cloud Functions 根据函数调用收费。(见定价


推荐阅读