Currently, I am querying for objects in the database to update. A snippet of the function that does so is
return getPostsForDate.get().then(snapshot => {
const updates = {}
var counter = 0
const batch = admin.firestore().batch()
snapshot.forEach((doc) => {
var key = doc.id
return admin.database().ref('/convoID/' + key).once('value', (snapshot) => {
if (snapshot.exists()) {
const convoIDCollection = snapshot.val()
for (var child in convoIDCollection) {
console.log(child)
updates["conversations/" + child] = null
updates["messages/"+ child] = null
updates["convoID/"+ child] = null
}
}
updates["/convoID/" + key] = null
updates["/reveals/" + key] = null
updates["/postDetails/" + key] = null
const postFireStoreRef = admin.firestore().collection('posts').doc(key)
const posterRef = admin.firestore().collection('posters').doc(key)
batch.delete(postFireStoreRef)
batch.delete(posterRef)
counter++
console.log(counter)
})
})
if (counter > 0) {
console.log("at the deletion point")
return Promise.all[admin.database().ref().update(updates), batch.commit()]
}
else {
console.log("null")
return null
}
})
Essentially, after the firestore queries for the posts, additional details are received from the realtime database and added to an array. Finally, I commit all these updates through a promise. However, the function that returns the updates is never reached - in order to ensure that updates are needed to the database, I have a counter that counts the number of updates. If it is greater than 0, I return
return Promise.all[admin.database().ref().update(updates), batch.commit()]
However, it seems like the return function is executed before the additional details are received, as it keeps on returning "null" to the console log which should only happen if the counter is less than 0.
Essentially, how do I wait for the data to be queried before executing the updates?
Update
return getPostsForDate.get().then(snapshot => {
const updates = {}
const promises = []
var counter = 0
const batch = admin.firestore().batch()
snapshot.forEach((doc) => {
promises.push (
admin.database().ref('/convoID/' + key).once('value', (snapshot) => {
if (snapshot.exists()) {
const convoIDCollection = snapshot.val()
for (var child in convoIDCollection) {
updates["conversations/" + child] = null
updates["messages/"+ child] = null
updates["convoID/"+ child] = null
}
}
updates["/convoID/" + key] = null
updates["/reveals/" + key] = null
updates["/postDetails/" + key] = null
const postFireStoreRef = admin.firestore().collection('posts').doc(key)
const posterRef = admin.firestore().collection('posters').doc(key)
batch.delete(postFireStoreRef)
batch.delete(posterRef)
counter++
})
)
})
Promise.all(promises).then(() => {
if (counter > 0) {
console.log("at the deletion")
return Promise.all[admin.database().ref().update(updates), batch.commit()]
}
else {
console.log("null")
return null
}
})
})
})