Firestore函数.onCreate触发器

时间:2020-05-19 08:18:04

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

我正在使用.onCreate发送关于集合的通知。

我的收藏集是tasks。给出新任务后,我需要向指定人员发送通知。

我需要保存token这个被分配的人吗?我只能获取那些已保存在文档中的值。 token的值在users集合中。

是否可以在函数中使用.where条件?

到目前为止,我的代码[将分配的人员的令牌与每个新任务条目一起保存在assignTo字段中::

    .document('todos/{todosId}')
    .onCreate(
        async (snapshot: { data: () => { (): any; new(): any; token: any; assignTo: any; text: any; name: any; profilePicUrl: any; }; }) => {

          // Notification details.
          const text = snapshot.data();
          const payload = {
            notification: {
            title: text.name,
             body: 'Notification body',
             icon: 'https://img.icons8.com/material/4ac144/256/user-male.png',
             click_action: `https://google.com`,
            }
          }; 

     const subscriber =   text.token;
    return admin.messaging().sendToDevice(subscriber, payload)
  });

.where条件是否可能?

集合“用户”获得token,其中assignTo == dwqhdiu78798u

编辑

这是我的代码,但函数给出了错误

    //  const subscriber = "evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_"; 
    const query = admin.firestore().collection('Students').where('Name', '==', 'caca');
    const querySnapshot = await query.get();
    const subscriber = querySnapshot.doc.data().token;
    return admin.messaging().sendToDevice(subscriber, payload)
  });

附加的屏幕截图:

enter image description here

函数错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您的问题是“在Cloud Function中,我可以通过包含where()子句的Query来获取Firestore数据”,答案是肯定的。

您应该使用Admin SDK,就像发送通知一样,如下所示:

const query = admin.firestore().collection('users').where('assignTo', '==', 'dwqhdiu78798u');
const querySnapshot = await query.get();
//....

根据您的评论进行更新并更新

您在以下行中收到错误(在添加到您的问题的代码中):

const subscriber = querySnapshot.doc.data().token;

这是因为QuerySnapshot没有doc属性。 QuerySnapshot包含一个或多个DocumentSnapshots。您应该使用docs数组或使用forEach()