gpt4 book ai didi

javascript - Firestore如何添加到子集合

转载 作者:行者123 更新时间:2023-12-02 23:56:04 25 4
gpt4 key购买 nike

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

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()返回一个您需要用来等待查询结果的 promise 。正如您的代码当前假设的那样,结果无法立即获得。

documentation显示如何处理异步查询结果的示例代码。由于您的代码使用了 async/await,因此您可以根据需要对其进行转换。请注意,您必须迭代从返回的 Promise 中获取的 QuerySnapshot 来查看是否找到文档。

关于javascript - Firestore如何添加到子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com