如何访问打字稿中的(firestore)文档ID或地址?

How to access the (firestore) document id or adress in typescript?

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

这是我 运行 函数的代码。我的问题是如何从文档中访问 {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);
    })

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

所以像这样:

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 文档。