Search code examples
javascriptdatabasefirebasereturnundefined

doc.data(); from firebase returns undefined but prints normally?


So I need to get data with a given id from a firebase collection. My function then should return it (the document) and in my test it should print (as the 'result'). For some reason, my test prints 'undefined' but my function (getIteration(id)) prints out exactly what I need it to return (at the console.log above the return). Why is it returning undefined but with the same doc.data() printing exactly what I need?

Here is my code:

//gets the iteration with the given id
async function getIteration(id) {
    fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
        snapshot.forEach(doc => {
            console.log(doc.data())
            return doc.data();
        })
    })
}

and my test:

firebase.getIteration(fbIterationID).then(function(result){
 console.log('LOGGING FB ITERATION DOCUMENT WITH THE ID OF: ' + fbIterationID)
    console.log(result)
})

Solution

  •     //gets the iteration with the given id
    async function getIteration(id) {
        return fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
            return snapshot.docs.map(doc => doc.data());
        })
    }