0

i want to find a way to retrieve my data from my cloud firestore and save it to an object so I can iterate through it, this was my attempt, but I'm sure this might be an array not an object

   async function findTrades() {

        const ref1 = admin.firestore().collection("bets");

        const snapshot = await ref1.get();
        const bets = [];
        snapshot.forEach(doc => {

            bets.push(doc.data());

        });

        const tokenIds = await Promise.all(results);

        return console.log("Here =>" + tokenIds);

    }

I want to be able to iterate through it like this

  bets.forEach(async match => { console.log(bets.id.name)

    });
mac
  • 65
  • 7

2 Answers2

0

doc.data() retrieves all fields in the doc document as an Object: let's call it a "doc Object".

Since you are looping on the results of a Query (to the entire bets collection), instead of pushing the doc Objects to an Array, you could create an object with these doc Objects, as follows.

const bets = {};
snapshot.forEach(doc => {

   bets[doc.id] = doc.data();

});

// Then you loop on the Object entries
for (let [key, value] of Object.entries(bets)) {
  console.log(`${key}: ${value}`);
}

See these answers for more ways on looping on an Object entries.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
0

You can't iterate over an object using a forEach loop. You do need an array for it.

async function findTrades() {
    const ref1 = admin.firestore().collection("bets");
    const snapshot = await ref1.get();
    const bets = {};

    snapshot.forEach(doc => {
        bets[doc.id] = doc.data();
    });

    console.log(bets)
}

You can try this code to get something like:

{
  "doc1Id": doc1Data,
  "doc2Id": doc2Data
}

But as I mentioned above you cannot use a forEach loop on this object. So it's good to have it as an array. Also if you try this code console.log(typeof bets) it'll log object even if it's an array.

Just in case you want it as a key-value pair and still use forEach, you can try this:

Object.keys(bets).forEach((betId) => {
  console.log(bets[betId]["name"])
})

Here betId is the document ID and name is just a field in that document.

PS: You can use a for loop as suggested by @Renaud.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84