I have been attempting to replicate a join statement in Firestore by associating a user with a comment through iterating over the comments collection. I am aware that querying a collection results in a promise and response, but I am uncertain about how to iterate over the documents in the response and execute another query within the loop.
Below is a simple example:
asyncData ({ params }) {
var postRef = Firestore.collection('posts').doc(params.post);
var commentRef =
Firestore.collection('posts').doc(params.post).collection('comments');
return commentRef.orderBy('created_on', 'desc').get().then(snapshot => {
var comments = []
snapshot.forEach(doc => {
var docData = doc.data()
comments.push({
comment: { data: doc.data(), id: doc.id }
})
})
return comments
})
.then(data => {
var comments = []
for(const comment of data) {
Firestore.collection('users-public').doc(comment.comment.data.created_by).get()
.then(doc => {
console.log('User Found!')
comments.push( {
comment: { data: comment.comment.data, id: comment.comment.id },
user: doc.data()
})
})
}
console.log("Ready to Return!")
return {comments: comments}
})
},
During execution, "Ready to Return!" gets logged before "User Found!" since the calls are asynchronous. I attempted using for...of without success. Is there a way to avoid this issue and wait for all async calls to complete before returning? It's crucial for me to resolve the promises to the User collection and use .data() to prevent a circular JSON error.