gpt4 book ai didi

javascript - 递归更新子集合/collectionGroup 的 Firestore 云函数

转载 作者:行者123 更新时间:2023-12-01 16:25:57 27 4
gpt4 key购买 nike

我有这个云函数:

import pLimit from "p-limit";


const syncNotificationsAvatar = async (
userId: string,
change: Change<DocumentSnapshot>
) => {
if (!change.before.get("published") || !change.after.exists) {
return;
}

const before: Profile = change.before.data() as any;
const after: Profile = change.after.data() as any;
const keysToCompare: (keyof Profile)[] = ["avatar"];
if (
arraysEqual(
keysToCompare.map((k) => before[k]),
keysToCompare.map((k) => after[k])
)
) {
return;
}

const limit = pLimit(1000);

const input = [
limit(async () => {
const notifications = await admin
.firestore()
.collectionGroup("notifications")
.where("userId", "==", userId)
.limit(1000)
.get()

await Promise.all(
chunk(notifications.docs, 500).map(
async (docs: admin.firestore.QueryDocumentSnapshot[]) => {
const batch = admin.firestore().batch();
for (const doc of docs) {
batch.update(doc.ref, {
avatar: after.avatar
});
}
await batch.commit();
}
)
);
})
];

return await Promise.all(input);
};


我如何递归更新 notifications 集合,但首先将查询限制为 1.000 文档(直到没有更多文档)然后 batch.update 他们?恐怕这个查询会超时,因为集合会随着时间的推移而变大。

最佳答案

发布我制定的解决方案,虽然没有遵循问题的上下文,但可以轻松组合。希望它能帮助别人。

import * as admin from "firebase-admin";

const onResults = async (
query: admin.firestore.Query,
action: (batch: number, docs: admin.firestore.QueryDocumentSnapshot[]) => Promise<void>
) => {
let batch = 0;
const recursion = async (start?: admin.firestore.DocumentSnapshot) => {
const { docs, empty } = await (start == null
? query.get()
: query.startAfter(start).get());
if (empty) {
return;
}
batch++;
await action(
batch,
docs.filter((d) => d.exists)
).catch((e) => console.error(e));
await recursion(docs[docs.length - 1]);
};
await recursion();
};

const getMessages = async () => {
const query = admin
.firestore()
.collection("messages")
.where("createdAt", ">", new Date("2020-05-04T00:00:00Z"))
.limit(200);

const messages: FirebaseFirestore.DocumentData[] = [];

await onResults(query, async (batch, docs) => {
console.log(`Getting Message: ${batch * 200}`);
docs.forEach((doc) => {
messages.push(doc.data());
});
});
return messages;
};

关于javascript - 递归更新子集合/collectionGroup 的 Firestore 云函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61454219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com