简体   繁体   中英

How to Trigger Firestore function on Creation of Sub Document in a sub Collection

I have a collection called pledges and inside it I have a field called pay to which is a collection that holders other subdocuments. I am writing a function to listen and get the newly created data in the sub-collection but I am not getting it right. My target is to get the id and the new doc and its data.

exports.createPayers = 
 functions.firestore.document("/pledges/{id}/payto/{payDocID}").onCreate(async (snap, context) 
  => {
  console.log("This is working");
  // get payer doc id
  const payerDocID = snap.id;

  // Get the payer Doc Data
  const payerDocData = snap.data().amountToPay;

  console.log(payerDocID.amountToPay + "is the pay id");
  return null;
});

在此处输入图像描述

// get payer doc id
const payerDocID = snap.id;

// Get the payer Doc Data
const payerDocData = snap.data().amountToPay;

console.log(payerDocID.amountToPay + "is the pay id");

payerDocID is a string (ID of new document created) and payerDocData is actually the value of amount to pay (number). You are trying to access the property amountToPay on a string which will log undefined is the pay id .

Try refactoring your code like this:

const payerDocID = snap.id

const payerDocData = snap.data() // no .amountToPay here

console.log(`PayerDocID: ${payerDocId}`)
console.log(`Amount to pay: ${payerDocData.amountToPay}`)
/pledges/{id}/payto/{payDocID}

If you need the parameters in wildcards ie id and payDocID , you can use context object:

const {id, payDocID} = context.params
console.log(id, payDocID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM