简体   繁体   English

从我的云 Firestore 中获取数据并将其保存到 Node JS 中的 Object

[英]Fetch data from my cloud Firestore and save it to an Object in Node JS

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我想找到一种方法从我的云 Firestore 中检索我的数据并将其保存到 object 以便我可以遍历它,这是我的尝试,但我确定这可能是一个数组而不是 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)

    });

doc.data() retrieves all fields in the doc document as an Object: let's call it a " doc Object ". doc.data()doc文档中的所有字段检索为 Object:我们称其为“ 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.由于您正在循环查询的结果(到整个bets集合),而不是将文档对象推送到数组,您可以使用这些文档对象创建 object,如下所示。

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.有关在 Object 条目上循环的更多方法,请参阅这些答案

You can't iterate over an object using a forEach loop.您不能使用 forEach 循环遍历 object。 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.但正如我上面提到的,你不能在这个 object 上使用 forEach 循环。 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.此外,如果您尝试此代码console.log(typeof bets) ,即使它是一个数组,它也会记录 object 。

Just in case you want it as a key-value pair and still use forEach, you can try this:以防万一您希望它作为键值对并仍然使用 forEach,您可以尝试以下操作:

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.这里betId是文档 ID,name 只是该文档中的一个字段。

PS: You can use a for loop as suggested by @Renaud. PS:您可以按照@Renaud 的建议使用 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM