【问题标题】:How to access the (firestore) document id or adress in typescript?如何在打字稿中访问(firestore)文档ID或地址?
【发布时间】:2020-06-17 11:24:16
【问题描述】:

我正在制作一个功能,一旦在他的帐户中添加了新的订单文档,它将发送到用户登录的所有设备。

这是我运行该函数的代码。我的问题是如何从文档中访问 {userEmail}/{orderId}。

export const orderUserNotif = functions.firestore
    .document('userAccounts/{userEmail}/orders/{orderId}')
    .onCreate(async snapshot => {

        const order = snapshot.data();

        const querySnapshot = await db
            .collection('userAccounts')
            .doc("{userEmail}") //Want to access the userEmail from the document address
            .collection('tokens')
            .get();

        const tokens = querySnapshot.docs.map(snap => snap.id);

        const payload: admin.messaging.MessagingPayload = {
            notification: {
                title: order!.title + " with ID " + '{orderId}', //Want to access order id here
                body: `Your order has been shipped`,
            }
        };

        return fcm.sendToDevice(tokens, payload);
    })

【问题讨论】:

    标签: typescript google-cloud-firestore push-notification google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    您可以使用context.params 访问触发云函数的路径中的值。 context 作为第二个参数传递给您的 Cloud Function,但您尚未声明它。

    所以是这样的:

    export const orderUserNotif = functions.firestore
        .document('userAccounts/{userEmail}/orders/{orderId}')
        .onCreate(async (snapshot, context) => {
    
            const order = snapshot.data();
    
            const querySnapshot = await db
                .collection('userAccounts')
                .doc(context.params.userEmail)
                .collection('tokens')
                .get();
    
            const tokens = querySnapshot.docs.map(snap => snap.id);
    
            const payload: admin.messaging.MessagingPayload = {
                notification: {
                    title: order!.title + " with ID " + context.params.orderId,
                    body: "Your order has been shipped",
                }
            };
    
            return fcm.sendToDevice(tokens, payload);
        })
    

    另请参阅 specifying a group of documents using wildcards 上的 Firebase 文档。

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2023-01-01
      • 1970-01-01
      • 2020-03-14
      • 2020-09-27
      • 2021-12-27
      • 1970-01-01
      • 2021-04-24
      • 2012-11-06
      相关资源
      最近更新 更多