如何高效利用Cloud Firestore引用类型跨文档访问目标文档?
直接通过DocumentReference访问目标文档的最优方式
你完全不用手动解析segments数组——Firestore返回的docrefs本身就是完整的DocumentReference实例,可以直接调用它的内置方法访问目标文档,这是最简洁高效的处理方式。
修改后的代码示例
exports.importProducts = functions.https.onRequest(async (request, response) => { const res = { success: false, error: "", productData: []}; const groceryListID = "groceryList1"; try { const groceryListDoc = await admin .firestore() .collection("GroceryList") .doc(groceryListID.toString()) .get(); if (!groceryListDoc.exists) { res.error = "Grocery list could not be found"; response.send(res); return; } const docReferences = groceryListDoc.data().docReferences; // 并行获取所有引用的文档,提升性能 const productDocs = await Promise.all(docReferences.map(ref => ref.get())); res.productData = productDocs .filter(doc => doc.exists) .map(doc => doc.data()); res.success = true; response.send(res); } catch (e) { res.error = "Error while reading the Grocery List document : " + e; response.send(res); } });
关键说明
- Firestore读取存储的引用字段时,会自动将其反序列化为
DocumentReference对象,而非普通JSON,所以你可以直接调用get()、update()等所有内置方法。 - 用
Promise.all()并行处理多个引用,比循环串行调用await效率更高,适合数组形式的多引用场景。 - 你看到的
{"_firestore":{"projectId":""},"_path":{"segments":["Products","p1"]},"_converter":{}}只是DocumentReference对象序列化后的JSON表现,实际代码中它是具备完整功能的实例。
内容的提问来源于stack exchange,提问作者Shiden67
相关产品推荐
相关产品推荐

