0

i am trying to get all docs in collection in firestore with node.js but i can't get any docs althow there is someone know what is the problem in this function:

exports.getTasksNew8 = functions.https.onRequest((request,response) => {
    admin.firestore().collection('users/admin/settings').get().then(querySnapshot=>{
        querySnapshot.forEach(documentSnapshot=>{
            console.log(documentSnapshot.id)
        })
    }).catch(error=>{
    console.log(error)
    })
    response.send('works ok)
})
J. Murray
  • 1,460
  • 11
  • 19
koby
  • 73
  • 2
  • 6

1 Answers1

3

The get() method is asynchronous and returns a Promise: you should "treat" the result within the then() method. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then and What does the function then() mean in JavaScript? and also https://scotch.io/tutorials/javascript-promises-for-dummies#toc-promises-are-asynchronous

By doing response.send('works ok)outside the then() you indicate to the Cloud Function that it can finish before the asynchronous get() is done.

Modify your code as follows:

exports.getTasksNew8 = functions.https.onRequest((request,response) => {
    admin.firestore().collection('users/admin/settings').get().then(querySnapshot=>{
        querySnapshot.forEach(documentSnapshot=>{
            console.log(documentSnapshot.id)
        })
        response.send('works ok);
    }).catch(error=>{
      console.log(error);
      //See the following video https://firebase.google.com/docs/functions/video-series#learn-javascript-promises-pt1-with-http-triggers-in-cloud-functions
    })

})
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121