如何发送从 firestore 数据库循环遍历数组的电子邮件



我正在尝试从电子商务商店发送用户收据。如何遍历要发送的数据

我尝试在动态数据上使用 []。

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();
// Sendgrid Config
import * as sgMail from "@sendgrid/mail";
const API_KEY = functions.config().sendgrid.key;
const TEMPLATE_ID = functions.config().sendgrid.template;
sgMail.setApiKey(API_KEY);
//FUNCTIONS
export const newOrder = functions.firestore
.document("checkout/{checkoutId}/products/{productId}")
.onCreate(async (change, context) => {
// Read booking document
const postSnap = await db
.collection("checkout/{checkoutId}/products")
.doc(context.params.productId)
.get();
const booking = postSnap.data() || {};
//Email
const msg = {
to: "wilmutsami@gmail.com",
from: "test@example.com",
templateId: TEMPLATE_ID,
dynamic_template_data: {
subject: "Hey there, thank you for your order!",
name: booking.name,
amount: booking.amount
}
};
//Send it
return sgMail.send(msg);
});

预期结果是向用户发送电子邮件,显示您订购的项目表

如果你想获取触发云checkout/{checkoutId}/products/{productId}功能的文档的数据

,你不需要做
await db
.collection("checkout/{checkoutId}/products")
.doc(context.params.productId)
.get();

如文档中所述:

当函数被触发时,它会提供数据的快照 与事件相关。您可以使用此快照读取或写入 添加到触发事件的文档,或使用 Firebase 后台 用于访问数据库其他部分的 SDK。

您可以通过snapDocumentSnapshot轻松获取文档字段的值,如下所示:

export const newOrder = functions.firestore
.document("checkout/{checkoutId}/products/{productId}")
.onCreate(async (snap, context) => {
const docData = snap.data();
const name = docData.name;
const amount = docData.amount;
// You can then use those values in the rest of your code
const msg = {
to: "wilmutsami@gmail.com",
from: "test@example.com",
templateId: TEMPLATE_ID,
dynamic_template_data: {
subject: "Hey there, thank you for your order!",
name: name,
amount: amount
}
};
return sgMail.send(msg);
});

最新更新