Firestore如何添加到子集合

我想在集合中找到一个文档,然后将项目添加到子集合(可能尚不存在):


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: []

}


叮当猫咪
浏览 183回答 1
1回答

皈依舞

您的“讨厌的事物”更接近事物的工作方式。第一次尝试将查询和文档创建结合在一个操作中。SDK根本无法正常工作。您正在使用任何给定的代码进行读取或写入,而不会一次都执行。您应该先进行查询,找到文档,然后使用它来创建更多文档。get()返回一个promise,您需要使用它来等待查询结果。正如您的代码当前所假设的那样,结果无法立即获得。该文档显示了如何处理异步查询结果的示例代码。由于您的代码使用异步/等待,因此您可以根据需要进行转换。请注意,您必须迭代QuerySnapshot从返回的Promise中获取的内容,以查看是否找到了文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript