简体   繁体   English

Firestore如何添加到子集合

[英]Firestore how to add to a sub collection

I would like to find a doc in a collection, and add items to a sub collection (which might not exist yet): 我想在集合中找到一个文档,然后将项目添加到子集合(可能尚不存在):

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

I was hoping for something like this: 我希望这样的事情:

// 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()

I ended up solving it like this but it's ugly, verbose and slow as it has to come back with a number of read ops first. 我最终像这样解决了它,但是它丑陋,冗长且缓慢,因为它必须首先返回许多读取操作。 Am I doing this right? 我这样做对吗?

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' });

Edit: 编辑:

The way I ended up handling this in a better way is a combination of flattening to other collections and also using arrays for stats. 我最终以更好的方式处理此问题的方法是将扁平化到其他集合,也将数组用于统计信息。 Feels much better: 感觉好多了:

// projects
{
  projectId1
}

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

Your "nasty thing" is much closer to the way things work. 您的“讨厌的事物”更接近事物的工作方式。

In your first attempt, you're trying to combine a query and a document creation in one operation. 第一次尝试将查询文档创建结合在一个操作中。 The SDK doesn't work like that at all. SDK根本无法正常工作。 You are either reading or writing with any given bit of code, never both at once. 您正在使用任何给定的代码进行读取或写入,而不会一次都执行。 You should do the query first, find the document, then use that to create more documents. 您应该先进行查询,找到文档,然后使用该文档来创建更多文档。

get() returns a promise that you need to use to wait on the results of the query. get()返回一个诺言,您需要使用该诺言来等待查询结果。 The results are not available immediately, as your code is currently assuming. 正如您的代码当前所假设的那样,结果无法立即获得。

The documentation shows example code of how to handle the results of an asynchronous query. 文档显示了如何处理异步查询结果的示例代码。 Since your code uses async/await, you can convert it as needed. 由于您的代码使用异步/等待,因此您可以根据需要进行转换。 Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found. 请注意,您必须迭代从返回的QuerySnapshot获取的QuerySnapshot ,以查看是否找到了文档。

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

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