首页 > 解决方案 > Firebase 云功能仅从数据库中读取众多数据快照之一

问题描述

我正在通过 CLI 读取 Firebase 数据库以获取我将发送通知的成员列表。通过满足一定条件的orderByChild查找数据库。问题是通知只发送给一个用户,尽管有许多满足条件的用途。我相信该函数只从数据库中读取一个用户。可能是异步等待用户不当的问题。有人可以帮忙吗。这是我的代码:

export const myfunction = functions.database.ref('/********/{*****Id}').onCreate(async (snapshot, context) => {

const *****Id = context.params.orderId
const mobile = snapshot.child('******').val()
const timeCreated = new Date

const ***DataBase = admin.database().ref()
const myRef = ***Base.child('users').orderByChild('****').equalTo('****')

const array:any = []
const snapshot2 = await myRef.once('value')
snapshot2.forEach(child => array.push(child))


for(const child of array){
    const key = child.key
    console.log(key)
    if(key!==null){
            const token = child.child('token').val()
            const payload = 
            {
                data:
                {
                    title: "Alert: ****",
                    body: "*****",
                    icon: "default"
                }
            }

            const options = {
                priority: "high"
            }

            await admin.messaging().sendToDevice(token, payload, options)
        }

}
})

基本上 array.push(child) 在 array[] 中只创建一个成员

标签: firebase-realtime-databasepromiseasync-awaitgoogle-cloud-functions

解决方案


经过深思熟虑,我可以找到自己的解决方案。问题不在于承诺或异步等待。它与 snapshot2.forEach(child => array.push(child)) 方法一起使用。在这里,除非我们特别提到 return false,否则 forEach 循环将在没有经过整个过程的情况下退出。因此解决方案是这样的:

snapshot2.forEach((child: any) => {
    array.push(child)
    return false
})

事情现在按预期工作


推荐阅读