I have a set of merchants and each merchant has a document and then a collection, each with nested documents and subcollections.
I created a loop so that every time the user clicks on the div, the function is called to get a snapshot of the next collection in the database.
But the function isn't calling because I'm trying to store the value of each document and collection in an array and then calling that array in the function to link the database to the web app (if that makes any sense).
But it's throwing an error of Uncaught TypeError: Cannot read properties of undefined (reading 'onSnapshot'). Any ideas on how to call the next document and subcollection in the database?
The output from the console.log for the join is: 'doc(Building Materials).collection(Building Materials)'
But the output from the console.log for the ref is: 'undefined'
Here is the code:
$(".outer-body").click(function(){
var src = $(this).text().trim();
sourceArray.push(src);
var doc;
var collection;
var dataArray = [];
for (var x = 0; x < sourceArray.length; x++){
var sourceX = sourceArray[x];
if(sourceArray[x] == sourceArray[0]){
doc = "doc(" + sourceX + ")";
} else {
doc = ".doc(" + sourceX + ")";
}
collection = ".collection(" + sourceX + ")";
dataArray.push(doc + collection);
}
var join = dataArray.join('');
console.log(join);
const ref = db.collection("all_merchants").doc(customClaim).collection(customClaim).join
console.log(ref);
ref.onSnapshot((querySnapshot) => {
console.log(doc.id, '=>', doc.data());
});
}
To make a document reference dynamic, you must update the function's argument.
'function(argument)' could probably not work as expected. This, on the other hand, will be: function('argument'). It's important to remember that these are functions, not strings.
The API surface of QueryDocumentSnapshot is identical to that of DocumentSnapshot. The exists() method will always return true, and getData() will never return null, because query results contain only existing documents.
I recommend using querySnapshot.exists() to see if the document you're looking for is actually there. That way, you'll be able to deal with any errors more effectively.
Remember to validate that the current version is V9, since this will make it easier to support you in the future.
Including a link of How to Avoid Getting "Cannot read property of undefined" in JavaScript that could also help.