【问题标题】:How to access all documents, my all documents only have sub collection in firestore如何访问所有文档,我的所有文档在 firestore 中只有子集合
【发布时间】:2021-04-10 14:26:40
【问题描述】:

我在 react native 中创建了这样的文档,我正在使用 rnfirebase 库

 firestore()
        .collection('WaterCanData')
        .doc(EntryDate)
        .collection('Entries')
        .doc(values.customerName)
        .set({
            CustomerName: values.customerName,
            CansOut: values.cansOut,
            JarsOut: values.jarsOut,
            EmptyCansIn: values.emptyCansIn,
            JarsIn: values.jarsIn,
            Bottles: values.bottles,
            Ice: values.ice
        })
        .then(() => {
            console.log('Entry added!!!!!!!!!');
        })

当我尝试从 WaterCanData Coellection 中检索 EntryDate 时,我无法获取它(文档名称以斜体字体显示),那么我应该如何检索包含子集合的文档,下面我附上了我的数据结构的 ss Data structure Data structuree

【问题讨论】:

  • 你要检索什么数据?
  • @suppa98 我想在 WaterCanData 中检索文档,即 EntryDate,我想要那些 EntryDate
  • 意思是要获取所有与abishek collection相关的数据?
  • @suppa98,是的,这将是下一步,但目前我想要保存在集合“WaterCanData”中的“EntryDate”列表。
  • 啊,你想得到 10042021。文件密钥?

标签: firebase react-native google-cloud-firestore


【解决方案1】:

您的文档以斜体显示的原因是它当前不存在。在 Cloud Firestore 中,子集合可以存在而无需其父文档也存在。

如 Firebase 控制台所述,不存在的文档不会出现在客户端 SDK 的查询或快照中。

此文档不存在,不会出现在查询或快照中

如果您希望能够获得您的入境日期,您需要创建文档(可以为空)。

firebase.firestore()
  .collection('WaterCanData')
  .doc(EntryDate)
  .set({}); // an empty document

要在创建文档的同时为其子集合中的条目创建文档,您可以像这样使用批量写入:

const db = firebase.firestore();
const batch = db.batch();

// get references to the relevant locations
const entryDateRef = db
  .collection('WaterCanData')
  .doc(EntryDate);
const customerRef = entryDateRef
  .collection('Entries')
  .doc(values.customerName);

// queue the data to write
batch.set(entryDateRef, {});
batch.set(customerRef, {
  CustomerName: values.customerName,
  CansOut: values.cansOut,
  JarsOut: values.jarsOut,
  EmptyCansIn: values.emptyCansIn,
  JarsIn: values.jarsIn,
  Bottles: values.bottles,
  Ice: values.ice
})

// make changes to database
batch.commit()
  .then(() => {
    console.log('Entry added!!!!!!!!!');
  });

这将允许您使用以下内容列出数据库中的所有条目日期:

firebase.firestore().collection('WaterCanData')
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach(doc => {
      const entryDate = doc.id;
      // const customerEntriesRef = doc.ref.collection('Entries');

      console.log('Entry date found: ' + entryDate);
    }
  });

如果(例如)您还想知道有多少条目链接到给定日期,您还需要查询每个子集合(这里的代码有点混乱)。

firebase.firestore().collection('WaterCanData')
  .get()
  .then((querySnapshot) => {
    const fetchSizePromises = [];

    // for each entry date, get the size of it's "Entries" subcollection
    querySnapshot.forEach(doc => {
      const entryDate = doc.id;
      const customerEntriesRef = doc.ref.collection('Entries');
      
      // if this get() fails, just store the error rather than throw it.
      const thisEntrySizePromise = customerEntriesRef.get()
        .then(
          (entriesQuerySnapshot) => {
            return { date: entryDate, size: entriesQuerySnapshot.size }
          },
          (error) => {
            return { date: entryDate, size: -1, error }
          }
        );

      // add this promise to the queue
      fetchSizePromises.push(thisEntrySizePromise)
    }

    // wait for all fetch operations and return their results
    return Promise.all(fetchSizePromises);
  })
  .then((entryInfoResults) => {
    // for each entry, log the result
    entryInfoResults.forEach((entryInfo) => {
      if (entryInfo.error) {
        // this entry failed
        console.log(`${entryInfo.date} has an unknown number of customers in its Entries subcollection due to an error`, entryInfo.error);
      } else {
        // got size successfully
        console.log(`${entryInfo.date} has ${entryInfo.size} customers in its Entries subcollection`);
      }      
    }
  });

【讨论】:

  • 关于列出日期的第一个代码不返回任何数据
  • 我会试试thanx,我还有一个问题是我的数据模型是否正确,在我刚接触firestore的情况下,构建数据的良好做法是什么。
【解决方案2】:

使用下面的代码,您可以控制 waterCanData 集合中的每个文档 ID。在您的数据库中,您只有一个文档,然后它将控制您的文档 ID。 (10042021)

firestore()
    .collection('WaterCanData')
    .get()
    .then((querySnapshot) => {
     querySnapshot.forEach((doc) => {
     console.log(doc.id)
     });
     })

【讨论】:

  • 正如 samthecodingman 所解释的,这不起作用,因为WaterCanDatacollection 下没有任何“正版”文档。
猜你喜欢
  • 2023-01-27
  • 2021-11-15
  • 2021-12-16
  • 1970-01-01
  • 2018-11-01
  • 2023-03-24
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多