'Can't fill array with firestore data

I'm trying to build a Firestore web app. I configured my database etc... And everything is right. But I'm now trying to get data from the firebase, store it in a variable (or fill array with those data) and do my computation on this variable that I will update every 30 sec (I do this to limit the number of query).

I can access to the data and read them without any problem but I can't add them. I've tried to put the variable in global, pass it through the function as argument but nothing works.

Here is my code:

userArray = [];

db.collection("scenario-name").get().then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          userArray.push(doc.id);
      });
});


console.log(userArray);

But I got something like this :

https://ibb.co/j3YdfLj

I also tried the .push.apply, or to define a function and pass userArray in it or even to do this kind of stuff :

userArray = [];

db.collection("scenario-name").get().then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          apply(doc);
      });
});

function apply(doc){
    userArray.push(doc.id);
}

Can I store a firestore query querying the whole document and work on it? Or should I do a query for every stuff? How can I store in a variable?

Thank you!



Solution 1:[1]

Your code appears pasted directly from Firestore documentation, so I would imagine that the issue is with the structure of the data, or the data, as it is stored in Firestore.

Get all documents in a collection

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

You are doing it right, creating an empty array variable then iterating your querySnapshot, pushing the ID of the document on each iteration. Validate what you are getting from the .get() using console.log. You should be good to go.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronnie Royston