如何基于两个集合文档使用云功能触发器

时间:2020-08-19 14:04:25

标签: javascript firebase google-cloud-firestore google-cloud-functions

我有一个ReferralCodes集合,其中指定的每个文档都具有这些值,其中'mine'值为false'msg'值为false而mycode是用户引用代码。

  appliedcode: ""
  mine:false
  msg:false
  mycode:"ASDF4G"
  referals : []

并且用户还有一个集合UserTransaction,该集合具有一个字段'CountTrans',当该值为1时,该字段被初始化为0我想触发一个函数来检查mine的值和applycode,如果mine的值为true并应用代码的值的长度为6,那么我想更新该用户的UserTransaction,并且Appliedcode是某个其他用户的参考代码,也希望更改该用户的UserTransaction

      const functions = require('firebase-functions');
  const admin = require('firebase-admin');


  const { user } = require('firebase-functions/lib/providers/auth');
 admin.initializeApp();

const db = admin.firestore();

exports.getCount= functions.firestore
.document('UserTransactions/{id}')
.onUpdate((change, context) => { 
const newTransdata = change.after.data();
const previousTransData = change.before.data();
const docid = context.params.docid;


if(newTransdata.CountTrans === 1) {
    const referalData = await 
admin.firestore.collection('ReferalCodes').doc(docid).get()
    const mine = referalData.mine;
    const appliedCode = referalData.appliedCode;
    let codes = [];
    var myfrindid;
    if(mine === true && appliedCode !== null) {
        const friendData = await 
admin.firestore.collection('ReferalCodes').doc('codes').get();
        var referalcodes = friendData['ReferalCodes'];
        referalcodes.forEach((items) =>{
            if (items['code'] == appliedCode) {
              myfrindid = items['id'];
            }
          });
        await 
admin.firestore.collection('ReferalCodes').doc(docid).update({
            msg: true
        })
    
    }else{

    }
}
});

1 个答案:

答案 0 :(得分:0)

向官方documents咨询的过程中,解释了如何处理数据库中的事件并根据需要触发一些不同类型的触发器,例如:

onWrite(),在实时数据库中创建,更新或删除数据时触发。

  • onCreate(),在实时数据库中创建新数据时触发
  • onUpdate(),在实时数据库中更新数据时触发
  • onDelete(),当从实时数据库中删除数据时触发

例如,传递给onUpdate处理函数的第一个参数是Change对象,该对象在DataSnapshot对象之前和之后都有两个属性。这些DataSnapshot对象描述了触发函数的更改前后的数据库内容。

exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
    const before = change.before  // DataSnapshot before the change
    const after = change.after  // DataSnapshot after the change
})