如何通过Firestore/Angularfire2查询budgets集合中budgetGroup的id?
查询Firestore嵌套对象字段的方法
嗨,我来帮你搞定这个问题!Firestore支持通过**点符号(.)**来查询嵌套对象里的字段,刚好适配你要查询budgetGroup.id的需求。
修改你的查询代码
你只需要在where条件里用budgetGroup.id作为字段路径,就能精准匹配嵌套对象的id了。比如可以调整你现有的方法,或者新增一个专门按预算组id查询的方法:
// 新增一个按预算组id查询的方法(更清晰) getBudgetsByGroupId(targetGroupId: string, projectId: string): AngularFirestoreCollection<Budget> { return this.fireStore.collection<Budget>(`projects/${projectId}/budgets`, ref => ref .where('budgetGroup.id', '==', targetGroupId) ); } // 如果你需要同时匹配budgetId和预算组id,就保留两个where条件 getSpecificBudgetWithGroup(budgetId: string, targetGroupId: string, projectId: string): AngularFirestoreCollection<Budget> { return this.fireStore.collection<Budget>(`projects/${projectId}/budgets`, ref => ref .where('id', '==', budgetId) .where('budgetGroup.id', '==', targetGroupId) ); }
为什么这样可行?
从你的model.ts可以看到,Budget类里的budgetGroup是一个BudgetGroup对象,在Firestore中它会被存储为一个嵌套的对象结构:
{ "id": "xxx", "amount": 1000, "budgetGroup": { "id": "group-123", "name": "运营预算", "creationTime": "xxx" }, // 其他字段... }
Firestore允许用字段名.嵌套字段名的形式来访问嵌套对象的属性,这样就能直接针对budgetGroup.id做过滤查询了。
注意事项
如果是同时使用多个where条件的复合查询,Firestore可能会要求你创建对应的复合索引。当你运行代码时,如果控制台抛出索引缺失的错误,里面会包含一个直接跳转Firestore控制台创建索引的链接,点击就能一键生成所需索引,非常方便。
内容的提问来源于stack exchange,提问作者Sampath
相关产品推荐
相关产品推荐

