gpt4 book ai didi

javascript - 批量获取DocumentReferences?

转载 作者:行者123 更新时间:2023-12-03 01:41:10 25 4
gpt4 key购买 nike

我正在尝试改进 firestore get 功能,我有类似的东西:

    return admin.firestore().collection("submissions").get().then(
async (x) => {
var toRet: any = [];
for (var i = 0; i < 10; i++) {
try {
var hasMedia = x.docs[i].data()['mediaRef'];
if (hasMedia != null) {
var docData = (await x.docs[i].data()) as MediaSubmission;

let submission: MediaSubmission = new MediaSubmission();
submission.author = x.docs[i].data()['author'];
submission.description = x.docs[i].data()['description'];

var mediaRef = await admin.firestore().doc(docData.mediaRef).get();
submission.media = mediaRef.data() as MediaData;
toRet.push(submission);
}
}
catch (e) {
console.log("ERROR GETTIGN MEDIA: " + e);
}
}
return res.status(200).send(toRet);
});

第一次获取很好,但性能最差:

var mediaRef = await admin.firestore().doc(docData.mediaRef).get();

我认为这是因为调用没有批量。

是否可以对 mediaRefs 数组进行批量获取以提高性能?

本质上,我有一个文档集合,其中包含由指向单独集合中的路径的字符串存储的外部引用,并且事实证明获取这些引用的速度很慢。

最佳答案

这个怎么办?我做了一些重构以使用更多的等待/异步代码,希望我的评论有帮助。

主要思想是使用Promise.all并等待所有mediaRefs检索

async function test(req, res) {
// get all docs
const { docs } = await admin
.firestore()
.collection('submissions')
.get();

// get data property only of docs with mediaRef
const datas = await Promise.all(
docs.map(doc => doc.data()).filter(data => data.mediaRef),
);

// get all media in one batch - this is the important change
const mediaRefs = await Promise.all(
datas.map(({ mediaRef }) =>
admin
.firestore()
.doc(mediaRef)
.get(),
),
);

// create return object
const toRet = datas.map((data: MediaSubmission, i) => {
const submission = new MediaSubmission();
submission.author = data.author;
submission.description = data.description;

submission.media = mediaRefs[i].data() as MediaData;

return submission;
});
return res.status(200).send(toRet);
}

关于javascript - 批量获取DocumentReferences?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840302/

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