簡體   English   中英

Firestore如何添加到子集合

[英]Firestore how to add to a sub collection

我想在集合中找到一個文檔,然后將項目添加到子集合(可能尚不存在):

projects (collection)
   project (doc)
      cluster (collection) // might not exist
        node1 (doc)  // might not exist
           statTypeA (collection)  // might not exist

我希望這樣的事情:

// Know the doc:
db.ref(`projects/${projectId}/cluster/node1/${statType}`).add()
// Or filter and ref:  
db.collection('projects').where(..).limit(1).ref(`cluster/node1/${statType}`).add()

我最終像這樣解決了它,但是它丑陋,冗長且緩慢,因為它必須首先返回許多讀取操作。 我這樣做對嗎?

const projectRefs = await db.collection('projects')
  .where('licenseKey', '==', licenseKey)
  .limit(1)
  .get();

if (!projectRefs.docs) {
  // handle 404
}

const projectRef = projectRefs.docs[0].ref;

const cluster = await projectRef.collection('cluster')
  .doc('node1').get();

await cluster.ref.collection(statType).add({ something: 'hi' });

編輯:

我最終以更好的方式處理此問題的方法是將扁平化到其他集合,也將數組用於統計信息。 感覺好多了:

// projects
{
  projectId1
}

// instances (to-many-relationship) (filter based on projectId)
{
  projectId
  statTypeA: []
  statTypeB: []
}

您的“討厭的事物”更接近事物的工作方式。

第一次嘗試將查詢文檔創建結合在一個操作中。 SDK根本無法正常工作。 您正在使用任何給定的代碼進行讀取或寫入,而不會一次都執行。 您應該先進行查詢,找到文檔,然后使用該文檔來創建更多文檔。

get()返回一個諾言,您需要使用該諾言來等待查詢結果。 正如您的代碼當前所假設的那樣,結果無法立即獲得。

文檔顯示了如何處理異步查詢結果的示例代碼。 由於您的代碼使用異步/等待,因此您可以根據需要進行轉換。 請注意,您必須迭代從返回的QuerySnapshot獲取的QuerySnapshot ,以查看是否找到了文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM