Mereics
Mereics

Reputation: 46

Getting data from Cloud Firestore

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!

Upvotes: 1

Views: 56

Answers (2)

vargaking
vargaking

Reputation: 149

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)

Upvotes: 1

Tarik Huber
Tarik Huber

Reputation: 7388

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.

Upvotes: 1

Related Questions