【问题标题】:How to send emails that loop through arrays from firestore database如何发送遍历来自firestore数据库的数组的电子邮件
【发布时间】:2019-10-22 14:08:12
【问题描述】:

我正在尝试从电子商务商店发送用户收据。如何循环发送数据

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

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);
});

预期结果是一封给用户的电子邮件,显示您订购的商品表

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions sendgrid


    【解决方案1】:

    如果你想在checkout/{checkoutId}/products/{productId}获取触发云函数的文档的数据你不需要这样做

    await db
      .collection("checkout/{checkoutId}/products")
      .doc(context.params.productId)
      .get();
    

    doc中所述:

    当一个函数被触发时,它会提供数据的快照 与事件相关。您可以使用此快照来读取或写入 到触发事件的文档,或使用 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);
    
    });
    

    【讨论】:

    • 好的,但是如何将数组从数据库发送到电子邮件?
    • 如果您查看 Sengrid 文档sendgrid.com/docs/ui/sending-email/…,您会发现您必须在 dynamic_template_data 对象中包含一个数组。
    • 我已经尝试关注它但仍然没有破解它。你能告诉我哪里出错了吗?
    • 您能否指出我做错了什么,我已尝试按照文档进行操作
    • 您在哪一部分有问题?在您的问题中,您没有解释要“循环发送要发送的数据”的数据。文档中有数组类型的字段?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多