So basically what I am trying is, access a document throught a reference attribut that is written in an other document like this:
Screen of the collection and the document that contains the references in an array
Here is the javascript function with which I would like to access the document. In this example I just return the reference attribut to see what it contains:
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);
// return 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);
//return res;
}
});
Here is the result I get when im reading the reference attribut:
Result in text format: {"success":true,"error":"","docrefs":{"_firestore":{"projectId":""},"_path":{"segments":["Products","p1"]},"_converter":{}}}
I know that I could parse the array elements of the "segments" to get the path and access to the document but is there a better way manage that? Maybe thanks a DocumentReference object?
The value that the SDK gives you back for a DocumentReference field type in the database is actually a DocumentReference object from the SDK too. So you can just call get() on the value you get, to get a snapshot of the references document data.