Essentially, my goal is to access a document through a reference attribute that is specified in another document like this:
Screenshot of the collection and the document containing references in an array
Below is the JavaScript function that I want to use to retrieve the document. In this example, I am simply returning the reference attribute to see its contents:
exports.importProducts = functions.https.onRequest(async (request, response) => {
const res = { success: false, error: "", docrefs: []};
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);
}
else {
const docref = groceryListDoc.data().docReferences;
res.success = true;
res.docrefs = docref[0];
response.send(res);
}
}
catch (e) {
res.error = "Error while reading the Grocery List document : " + e;
response.send(res);
}
});
This is the result when examining the reference attribute:
The resulting data in text format: {"success":true,"error":"","docrefs":{"_firestore":{"projectId":""},"_path":{"segments":["Products","p1"]},"_converter":{}}}
I am aware that I could parse the elements of the "segments" array to access the path and eventually reach the document, but is there a more efficient way to handle this? Perhaps utilizing a DocumentReference object?