我想知道我是否正确地为我的 Firestore 数据模型建模,因为我意识到当前的方式会导致对服务器的大量请求。
上下文:
我有一个练习
集合。
{
exercises: {
abc123: {
name: "Squat",
vidUrl: 'https://example.com'
},
bcd234: {
name: "Push Up",
vidUrl: 'https://example.com'
}
}
}
我有一个workouts
集合。当我加载特定的锻炼时,我会循环加载各个步骤的练习并将它们映射到原始响应。
{
workouts: {
uniqueId: {
name: 'Strength',
circuits: [{
steps: [
{
duration: 45,
exerciseId: 'abc123'
},
{
duration: 30,
exerciseId: 'bcd234'
}
]
}]
}
}
}
这是最好的方法吗?还是我应该首先将锻炼数据映射到步数?
此外,这种数据建模是否会导致难以更新 circuits.steps
,因为它是一个嵌套数组?
最佳答案
I realise the current way will result in a lot of requests to the server.
Firestore 中的查询很浅,这意味着它们仅从运行查询的集合中获取项目。无法在单个查询中从两个顶级集合中获取文档。因此,在您的情况下,您需要查询数据库两次,一次是从 steps
数组中获取每个 exerciseId
,然后根据该 ID,您需要获取每个特定的运动。
根据有关 usage and limits 的官方文档,Firestore 中的所有内容都与读写次数有关。
根据您的评论:
for each exerciseId in the
steps
array in the workouts collection, I am querying to get each exercise.
要减少读取次数,您可以在 steps
数组下方托管整个 exercise
对象。这意味着您只需查询一次数据库,因为您需要的一切都已经存在。这种做法称为 非规范化
,是 Firebase 的常见做法。如果您是 NoQSL 数据库的新手,我建议您观看此视频,Denormalization is normal with the Firebase Database为了更好地理解。它适用于 Firebase 实时数据库,但同样的规则适用于 Cloud Firestore。
此外,当您复制数据时,需要牢记一件事。以与添加数据相同的方式,您需要维护它。换句话说,如果你想更新/删除一个练习,你需要在它存在的每个地方进行。
关于database - 减少请求的 Firestore 数据建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915865/