简体   繁体   中英

Firebase Cloud Functions - How to query a collection, iterate over it and then run functions for each document?

With as prolific as Firebase is, I'm a bit surprised to find that I can't seem to find much documentation on how to query a collection for a set of documents (of which the ID is not known), and then perform some logic based on properties of each those documents.

In my particular example, all I'm trying to do is query a collection of pending payments based on if the charge date has passed and then process the charge with Stripe. So far, I haven't had any luck in running the function and I get this error:

TypeError: functions.firestore.collection is not a function
    at exports.chargePendingStripeAccounts.functions.pubsub.schedule.onRun (/srv/lib/index.js:78:32)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:127:23)
    at /worker/worker.js:825:24
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Here is my code for the function

exports.chargePendingStripeAccounts = functions.pubsub.schedule('every 2 minutes').onRun((context) => {

  return functions.firestore.collection('payments', (ref) => ref.where('charge_date', '>=', new Date())).get()
    .then(payments => {

      payments.forEach(doc => {
        const data = doc.val();
        const amount = data.price * 100;
        const idempotency_key = data.creator_id;  // prevent duplicate charges
        const source = data.token.id;
        const currency = 'USD';
        const charge = {amount, currency, source};

        return stripe.charges.create(charge, { idempotency_key });
      })

    });
});

Surely there's a way to do this in Cloud Functions, right?

It looks like you're trying to use the Cloud Functions for Firebase SDK to make a query to Cloud Firestore. That's not going to work. The Functions SDK (in your code, identified by functions ) just lets you declare triggers that run in response to changes in your project. If you want to query Cloud Firestore, you will have to use one of the server SDKs available for nodejs. You can use the SDK provided by Google Cloud , or you can use the Firebase Admin SDK , which just wraps the Cloud SDK.

Pretty much all of the official samples provided by the Firebase team use the Admin SDK where appropriate, so you can use those as examples.

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