Firebase Cloud Functions - 如何查询集合,对其进行迭代,然后为每个文档运行函数?



尽管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 for Firebase SDK 向 Cloud Firestore 进行查询。 这是行不通的。 函数 SDK(在代码中,由functions标识(仅允许您声明为响应项目中的更改而运行的触发器。 如果要查询 Cloud Firestore,则必须使用可用于 nodejs 的服务器 SDK 之一。 您可以使用 Google Cloud 提供的 SDK,也可以使用 Firebase Admin SDK,它只包装了 Cloud SDK。

Firebase 团队提供的几乎所有官方示例都在适当的情况下使用管理员 SDK,因此您可以将这些示例用作示例。

最新更新