【问题标题】:Error with Firestore update in a Cloud FunctionCloud Function 中的 Firestore 更新出错
【发布时间】:2018-06-06 21:58:06
【问题描述】:

我尝试在 Firebase 上放置一个侦听器,该侦听器将复制 Firestore 中匹配元素中的值。

exports.synchronizeDelegates = functions.database.ref(`delegates/{userId}/activities`).onUpdate((event) => {
        const userKey = event.data.ref.parent.key

        console.log("User Key:" + userKey)

        return admin.database().ref(`delegates/${userKey}/email`).once('value', snapshot => {

            let email = snapshot.val()

            console.log("Exported Email:" + email)

            const userRef = admin.firestore().collection('users')
            const firestoreRef = userRef.where('email', "==", email)

            firestoreRef.onSnapshot().update({ activities: event.data.toJSON() })

        }).then(email => {
            console.log("Firebase  Data successfully updated")
        }).catch(err => console.log(err))
    }
)

此函数能够检索和定位在firestore中定位正确文档所需的元素,但.update()函数仍然错误firestoreRef.update is not a function 我尝试了几种查询方法,但仍然出现此错误。

在这种情况下如何正确查询并更新文档?

【问题讨论】:

  • 你有没有试过用这个替换那行:firestoreRef.update({ activities: event.data.toJSON() })
  • 是的,我尝试在查询之后链接 update() 方法,它返回相同的错误。
  • 顺便说一句:我喜欢您使用 Cloud Functions 将 Cloud Firestore 同步到实时数据库。
  • 我不确定@FrankvanPuffelen 有多大的讽刺意味,但在我的情况下,我的 RTDB 中的 activities 字段是由第三方供应商更新的,该供应商通过API。当我为我的客户视图继续使用 Firestore 时,这是我发现使其工作的最快方法,因为此时我无法控制第三方开发。下一步将很明显,更新第三方提供程序以在 Firestore 中写入
  • 一点也不讽刺。对不起,如果它是这样的。我一直想为我的一些项目编写这样的 RTDB 到 Firestore 同步功能,但是……太多其他的东西不断出现。很高兴看到至少有人做到了。 :-)

标签: javascript firebase firebase-realtime-database google-cloud-functions google-cloud-firestore


【解决方案1】:

QueryonSnapshot() 方法引入了一个持久侦听器,每次有新的 QuerySnapshot 可用时都会触发该侦听器。它一直这样做,直到侦听器被取消订阅。这种行为绝对不是你想要的。此外,您的代码尝试调用的 QuerySnapshot 上没有 update() 方法。

相反,您似乎想使用get() 来获取与您的查询匹配的文档列表,然后将它们全部更新:

exports.synchronizeDelegates = functions.database.ref(`delegates/{userId}/activities`).onUpdate((event) => {
    const userId = event.params.userId
    console.log("User Key:" + userKey)

    return admin.database().ref(`delegates/${userId}/email`).once('value', snapshot => {

        let email = snapshot.val()

        console.log("Exported Email:" + email)

        const usersRef = admin.firestore().collection('users')
        const query = usersRef.where('email', "==", email)

        const promises = []
        query.get().then(snapshots => {
            snapshots.forEach(snapshot => {
                promises.push(snapshot.ref.update(event.data.val()))
            })
            return Promise.all(promises)
        })
    }).then(email => {
        console.log("Firebase  Data successfully updated")
    }).catch(err => console.log(err))
}

请注意,我在您的函数中重写了其他一些不是最佳的内容。

一般来说,最好熟悉 Cloud Firestore API 文档以了解您可以做什么。

【讨论】:

  • 感谢您的意见@Doug event.params.userId也是一个很好的学习。
猜你喜欢
  • 2018-03-22
  • 1970-01-01
  • 2020-07-02
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 2020-01-11
相关资源
最近更新 更多