我试图获取集合中的所有文档,.forEach
文档对子集合进行查询,并从中获取最新(按日期)文档,但由于某种原因,查询大小始终为0
下面是代码:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
/// Updates the last payment done in the neighbors documents
export const updateLastPaymentHTTP = functions.https.onRequest(
async (request, response) => {
try {
const neighbors = await admin.firestore()
.collection("neighbors").get();
const promises = [];
neighbors.forEach(async (neighbor) => {
const topPaymentRef = admin.firestore()
.collection(`neighbors/${neighbor.ref}/payments`)
.orderBy("date", "desc")
.limit(1)
.get();
const querySize = await topPaymentRef.then((query) => query.size);
console.log(`Query Size: ${querySize}`);
if (querySize === 1) {
const lastPayment = (await topPaymentRef).docs[0].data();
promises.push(neighbor.ref.update({ last_payment: lastPayment }));
} else {
promises.push(neighbor.ref.update({ last_payment: "" }));
}
});
await Promise.all(promises);
response.send("Update Last Payments Completed");
} catch (error) {
console.log(`Error Updating Last Payment ${error}`);
}
}
);
我做查询检查是因为在一些邻居文档中没有一个名为payments的子集合,但在大多数邻居文档中有:
With Payments
和/或
Without Payments
但是我的querySize === 1
总是false,我更新了{ last_payment: '' }
。我也尝试了解释here的每个选项,我的集合查询有什么问题吗?
2条答案
按热度按时间jgwigjjp1#
代码中有几个地方需要调整:
async/await
和then()
弄混了forEach
循环中使用async/await
(不推荐使用,请参阅https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404)以下内容应该有效(未经测试):
iszxjhcz2#
跟进Renaud代码和Doug解决方案,我发现问题与
neighbor.ref
有关,我将其更改为neighbor.ref.id
,然后一切正常,以下是我在Renaud代码中的更改:首先,我添加了一个常量,以便保存每个邻居的id并将它们添加到列表中:
然后,在获得所有邻居的promise之后,我创建了一个名为
refDoc
的变量,以保存每个查询的所有引用,并相应地更新文档。希望这对其他人有帮助。