【问题标题】:How to loop each document and get its data如何循环每个文档并获取其数据
【发布时间】:2020-04-22 18:24:38
【问题描述】:

我是 javascript 新手,也是 Firebase 云函数的新手,我想知道如何迭代我的查询返回的每个文档并从每个文档中获取我用户的 deviceToken,这就是我所做的

    let docRef = db.collection('user').doc(userId);
    let shopUserRef = db.collection('user').where('shop', '==', shopId);

    var orderStatusDetail;
    var notificationTitle;
    switch(orderStatus){
        case 0:
            notificationTitle = "You have a new order ! ????️"
            orderStatusDetail = String("A new order has arrived, check it out")
            docRef = shopUserRef;
            break;
        case 1:
            notificationTitle = "Hey there! ????"
            orderStatusDetail = "✅ Your order is ready"
            break;
}

 return docRef.get().then(userDoc => {
       const deviceToken = userDoc.data().deviceToken
        const payload = {
        notification: {
            title: notificationTitle,
            body: orderStatusDetail
        }
    }
        console.log("userId:"+userId+"orderstatus:"+orderStatus+"deviceToken"+deviceToken)
        return admin.messaging().sendToDevice(deviceToken,payload)
  });

所以,这段代码的作用很简单,如果 case 为 0 (orderStatus == 0),我只需要向商店的所有者发送通知,这就是为什么我使用另一个引用来获取该用户设备令牌,但这里可能有超过 1 个用户拥有该商店 ID,因此我想迭代这些文档以获取每个 ID 并向他们发送新订单的所有通知。

这里的 docRef 只是购买了产品的客户,需要通知他们。

但在case 0我需要向所有店铺客户ID发送通知

我想知道如何在这里循环

return docRef.get().then(userDoc => {
   for(user in userDoc) {
    // I dont know if this is the correct for loop way to get each document data
}
...

【问题讨论】:

    标签: javascript firebase google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    查看https://firebase.google.com/docs/firestore/query-data/queries#execute_a_query

    听起来你正在寻找

    docRef.get()
        .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
            });
        })
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        });
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2019-09-08
      • 2021-12-25
      • 2022-06-19
      • 1970-01-01
      相关资源
      最近更新 更多