Home > Back-end >  how do i write a Firebase cloud function to update a collection based on the data in another collect
how do i write a Firebase cloud function to update a collection based on the data in another collect

Time:10-21

I have been trying to add a feature of automatic email to myself if the value in a certain field goes below certain number. my database looks like this firestore database

I want to write a cloud function that automatically adds data to the mail collection which then triggers an email using Firebase Trigger Email. The trigger I'm looking for is the price_change(which is in string format, therefore I'm trying to convert it to int inside the cloud function) and compare it and update mail collection.

my code looks like this. how do i fix it?

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: '[email protected]',
        message: {
          subject: 'big change in bitcoin prices!',
          html: 'This is an <code>HTML</code> email body.',
        },
      });}
  });

CodePudding user response:

Since adding a document to Firestore is an asynchronous operation, you need to return the promise from that operation. Without that, Cloud Functions will likely terminate your code before it gets a chance to write the document.

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({ //            
  • Related