Reputation: 266
I have a query that gets a document collection, then iterates over the collection of returned documents looking up additional data. This is done in a forEach
loop, adding the document to an array returning Promise.all(array)
.
From here I can chain another then(snapshot => { })
to get the items in the array returned from the Promise, however the problem is when I invoke the method data()
to get a plain old javascript object it's always returning undefined
. I'm not sure how to resolve this.
Here's the Firebase Cloud Function:
exports.cloudFunctionApi = functions.https.onCall(async(data, context) => {
admin.firestore().collection("myDocuments").get()
.then(snapshot => {
const promises = []
snapshot.forEach(item => {
if(item.id == "abc123") {
const data = item.data()
const p = admin.firestore().doc(`myDocumentDetail/${item.id}`).get()
promises.push(p)
}
})
return Promise.all(promises)
})
.then(snapshot => {
snapshot.forEach(item => {
const data = item.data()
console.log(`data is: ${data}`) // <- data is undefined
})
})
.catch(error => {
console.error(`Error: ${error}`)
})
})
I was getting some dumb warnings about const promises = []
which I resolved in tsconfig.json file, the settings are:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"target": "es2017",
"resolveJsonModule": true
},
"compileOnSave": true,
"include": [
"src"
],
"strictNullChecks":false
}
Upvotes: 1
Views: 1111
Reputation: 266
Murphy's law, as soon as you post a question you figure out the answer.
In tsconfig.json
I added "strict": true
and for the declaration of my array, I changed the code to be const promises:any[] = []
. This was the only way I could resolve the "dumb error", but as Doug Stevenson posted, you could also use const promises: Promise<FirebaseFirestore.DocumentSnapshot>[] = []
for typesafety.
Next I removed the document from the collection and re-added it back with the same document identifier. Sure enough, I'm no longer seeing undefined
but instead the full object representation. Yah!
Upvotes: 0
Reputation: 317412
When data() returns undefined, according to the linked API documentation, that means the document you requested with get()
doesn't exist. Since we can't see your data, or any of the variables in your code, you're going to have to do some debugging to figure out why that is.
I suggest putting a check for data.exists
in your code so you can find out if the requested document exists before calling data()
, or simply checking the result of data()
before trying to act on it.
Upvotes: 1