【问题标题】:How can I compare two documents ?(firestore onUpdate)如何比较两个文档?(firestore onUpdate)
【发布时间】:2020-10-29 11:40:27
【问题描述】:

所以我想在文档上使用 onUpdate 触发器来获取前后的差异。

下面是它之前的样子:

之后:

所以在示例中,文档之间的区别是“zfb5gXV54f5jbfn438Hd”。有了它,我将在我的应用程序的其他地方使用它。

这是我目前所拥有的:

export const someFunc = functions.firestore.document('invites/{invitesUID}').onUpdate(async (change, context) => { 
    const previousValue = change.before.data();
    const newValue = change.after.data();
    })

因此,通过 onUpdate,我将能够获得所需的信息。我应该采取什么方法呢?我有一些想法,但想知道是否有更好的方法来做到这一点。一如既往,感谢您的帮助!

更新:

所以我想出了这个:

export const deleteMember = functions.firestore.document('invites/{invitesUID}').onUpdate(async (change, context) => {
    const previousValue = change.before.data()['invites']
    const newValue = change.after.data()['invites']
    if (previousValue.length > newValue.length) {
        
        const prevInviteListArray = Object.entries(previousValue)
        const newInviteListArray = Object.entries(newValue)
        let difference = prevInviteListArray.filter((x: any) => !newInviteListArray.includes(x));

        console.log('old list: ' + prevInviteListArray)
        console.log('new list: ' + newInviteListArray)
        console.log('the difference: ' + difference)
    }
})

得到了这个结果:

不知道为什么过滤器不起作用...有什么想法吗? (还有我怎样才能看到对象中的内容?)

【问题讨论】:

    标签: typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您已经在正确的轨道上,onUpdate 触发器将在更改之前/之后提供文档。从那里您决定如何比较两个对象以确认发生了哪些更改,这完全取决于您。如果您正在寻找示例,您可以查看documentation


    代码event.before.data() 返回一种Javascript Hashmap,您可以像往常一样访问它,同样的事情也适用于Firestore 文档中的数组字段,对您而言,它们只是JS 数组。我使代码工作如下:

    export const deleteMember = functions.firestore.document('invites/{invitesUID}').onUpdate(async (change, context) => {
        const previousValue = change.before.data()['invites']
        const newValue = change.after.data()['invites']
        if (previousValue.length > newValue.length) {
            let difference = previousValue.filter(x => !newValue.includes(x));
            console.log('old list: ' + previousValue)
            console.log('new list: ' + newValue)
            console.log('the difference: ' + difference)
    

    【讨论】:

    • 嘿,我更新了我的问题,你能看一下吗?
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2010-09-15
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多