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!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.