![](/img/trans.png)
[英]Run transaction regardless if collection/document exists - Firestore - Cloud Functions
[英]Firebase Cloud Functions - How to query a collection, iterate over it and then run functions for each document?
與Firebase一樣多產,令我感到驚訝的是,我似乎找不到太多關於如何查詢集合中一組文檔(其ID未知)的文檔,然后執行一些操作。邏輯基於每個文檔的屬性。
在我的特定示例中,我要做的就是根據收費日期是否過去來查詢待付款項的集合,然后使用Stripe處理收費。 到目前為止,我在運行該函數時沒有任何運氣,但出現此錯誤:
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)
這是我的功能代碼
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 });
})
});
});
當然,在Cloud Functions中可以找到一種方法,對嗎?
您似乎正在嘗試使用Cloud Functions for Firebase SDK來查詢Cloud Firestore。 那是行不通的。 Functions SDK(在您的代碼中,由functions
標識)僅允許您聲明觸發以響應項目中的更改而運行的觸發器。 如果要查詢Cloud Firestore,則必須使用可用於nodejs的服務器SDK之一。 您可以使用Google Cloud提供的SDK ,也可以使用Firebase Admin SDK (僅包裝Cloud SDK)。
Firebase團隊提供的幾乎所有正式示例在適當的地方都使用Admin SDK,因此您可以將其用作示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.