1

I am struggling to get data out of the Firestore Cloud. The problem is that I have a function and inside it I have the data from the database, but I can't get it out of the function. I'll attach the code below.

function logBook(doc){
    let names = doc.data().name;
    console.log(names);
}



db.collection('flights').get().then((snapshot) =>{ 
    snapshot.docs.forEach(doc => {
        logBook(doc);
    });
})

console.log(names);

Console output: https://prnt.sc/1bgrice

Thanks!

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Mereics
  • 46
  • 7

2 Answers2

1

You are probably missing the fact that if you use then in a fucntion that it will leave the syncronous flow of the function and you can't return a result as you would expect it to.

Try a code like this:

function logBook(doc) {
  let names = doc.data().name;
  console.log(names);
}

async function getData() {
  const result = [];

  const snapshot = await db.collection("flights").get();

  snapshot.docs.forEach((doc) => {
    logBook(doc);
    result.push(doc);
  });

  return result;
}

It is very importand here to undertand the async nature of the Firestore SDK.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
1

The answer is much more simplier, than you think. You just have to declare a variable outside the function, than assign value to it inside the function. Something like this:

var globalVar;

function logBook(doc){
    let names = doc.data().name;
    globalVar = names;
    console.log(names);
}



db.collection('flights').get().then((snapshot) =>{ 
    snapshot.docs.forEach(doc => {
        logBook(doc);
    });
})

console.log(names);

Also if you assign a variable with the let keyword, it'll be scoped inside the function. I can recommend you this topic: What's the difference between using "let" and "var"?

(if you don't wanna spam stack with your starter questions, you can contact me on dc: vargaking#4200)

vargaking
  • 129
  • 1
  • 10