【问题标题】:Query firestore to get all tokens from userid's查询 firestore 以从 userid 获取所有令牌
【发布时间】:2018-10-31 11:59:35
【问题描述】:

在我的云函数中,我有一个数组,其中包含需要获取云消息(通知)的所有用户 ID

const aNotify = [{id: 'id001', text: 'specialTextFor001'}, {id: 'id002', text: 'specialTextFor002'};

这就是设备集合的样子。文档 ID 是令牌 ID,但要找到它们,我需要查询 userId

是否可以像使用 where 子句一样通过 DB 来做到这一点,还是我需要通过获取所有设备并在云方法中执行 foreach 来做到这一点...?

【问题讨论】:

  • CollectionReference 的get() 函数返回一个promise,该promise 将与查询结果一起解决。将所有 promise 收集到一个 List 中,并将其传递给 all() 函数以在整个集合完成时做出响应,正如 here 所解释的那样,对吧?
  • @AlexMamo 您的意思是在 userId 上创建每个“where”子句的承诺列表?那岂不是矫枉过正?
  • 是的。它不会。请参阅此post 中的 Doug 的回答。适用于 Android,但您可以在网络上实现相同的目标。

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


【解决方案1】:

为了找到与userId 对应的device 文档,您必须使用如下简单查询:

const db = admin.firestore();
db.collection('devices').where("userId", "==", element.id).get();

参见相应的文档here

由于您需要对aNotify 数组的每个元素进行查询,因此您需要使用Promise.all(),因为get() 返回一个Promise。

以下内容将起作用。您必须对其进行调整才能正确返回 Cloud Function 中的 Promise(由于您没有共享您的 Cloud Function 代码,因此很难在这一点上提供更多指导)。

    const db = admin.firestore();

    var aNotify = [{ id: 'id001', text: 'specialTextFor001' }, { id: 'id002', text: 'specialTextFor002' }];

    var promises = []
    aNotify.forEach(function (element) {
        promises.push(db.collection('devices').where("userId", "==", element.id).get());
    });
    return Promise.all(promises)   
        .then(results => {
            results.forEach(querySnapshot => {
                querySnapshot.forEach(function (doc) {
                    console.log(doc.id, " => ", doc.data());
                    //here, either send a notification for each user of populate an array, or....
                    //e.g. return admin.messaging().sendToDevice(doc.data().token, ....);
                });
            });
        });

请注意,results 数组的顺序与promises 数组的顺序完全相同。所以发送通知时获取aNotify数组对应对象的text属性并不复杂。

【讨论】:

  • 感谢您的帮助,但这将使用分配网络呼叫对吗?我指的是这部分 promises.push(db.collection('devices').where("userId", "==", element.id).get());
  • @MichaelAngelo 它将通过 userId 查询一个文档(假设 userId 仅与一个设备相关联)。使用您的数据模型没有其他方法......或者您将数据非规范化并将任何内容放入一个文档中,例如在一个数组中。但是您必须注意 Firestore 的限制,请参阅 firebase.google.com/docs/firestore/quotas#limits
猜你喜欢
  • 2021-10-22
  • 2022-01-16
  • 2017-08-21
  • 2018-11-07
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
相关资源
最近更新 更多