node.js - 如何发送遍历来自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 Admin SDK 访问数据库的其他部分。
您可以通过以下方式轻松获取文档字段的值snap
DocumentSnapshot
:
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);
});
推荐阅读
- c# - 统一要求身体变量
- discord - 如何通过 discord.js 中 DM 中发送的命令检查用户是否在特定服务器中具有特定角色?
- python - 在创建电报机器人时,终端正在争论第 8 行中的“文本”
- google-apps-script - 无法将参数从云函数传递到谷歌应用程序脚本并返回响应
- spring-boot - Maven 中缺少 Asciidoctor “Snippets”
- google-apps-script - 如何使用 GMAIL API 从 Google Apps 脚本发送电子邮件?
- flutter - 元素类型“问题”不能分配给列表类型“小部件”
- android - 尝试从 firebase 检索数据,但未显示数据
- python - python3.7.9忘记框架
- apache2 - 带有 HTTP Basic/Digest 身份验证的 Gerrit 3.2.3:无法启动服务