![](/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.