【问题标题】:how do i write a Firebase cloud function to update a collection based on the data in another collection.?我如何编写一个 Firebase 云函数来根据另一个集合中的数据更新一个集合。?
【发布时间】:2021-12-07 14:20:59
【问题描述】:

如果某个字段中的值低于某个数字,我一直在尝试为自己添加自动电子邮件功能。我的数据库看起来像这样firestore database

我想编写一个云函数,自动将数据添加到邮件集合中,然后使用 Firebase Trigger Email 触发电子邮件。我正在寻找的触发器是 price_change(它是字符串格式,因此我试图在云函数中将其转换为 int)并比较它并更新邮件集合。

我的代码如下所示。我该如何解决?

exports.btcMail = functions.firestore
  .document('cryptos/Bitcoin/1h/{wildcard}')
  .onWrite((change, context) => {
    const newval = change.data();
    console.log(newval)
    const price = ParsInt(newval.price_change())
    if (price < -200) {
      admin.firestore().collection('mail').add({
        to: 'someone.someone@gmail.com',
        message: {
          subject: 'big change in bitcoin prices!',
          html: 'This is an <code>HTML</code> email body.',
        },
      });}
  });

【问题讨论】:

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


    【解决方案1】:

    由于将文档添加到 Firestore 是一项异步操作,因此您需要从该操作中返回 Promise。否则,Cloud Functions 可能会在您有机会编写文档之前终止您的代码。

    exports.btcMail = functions.firestore
      .document('cryptos/Bitcoin/1h/{wildcard}')
      .onWrite((change, context) => {
        const newval = change.data();
        console.log(newval)
        const price = ParsInt(newval.price_change())
        if (price < -200) {
          return admin.firestore().collection('mail').add({ // ? add return here
            to: 'someone.someone@gmail.com',
            message: {
              subject: 'big change in bitcoin prices!',
              html: 'This is an <code>HTML</code> email body.',
            },
          });
        } else {
          return null; // ? Add a return here to prevent paying longer than needed
        }
    
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      相关资源
      最近更新 更多