我正在制作一个函数,一旦用户在其帐户中添加了新的订单文档,该函数将发送到用户登录的所有设备。
这是我运行函数的代码。我的问题是如何从文档中访问 {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
从触发云函数的路径访问值。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);
})
另请参阅 Firebase 文档,了解如何使用通配符指定一组文档。