我在 Flutter 应用程序中使用嵌套集合从 Firestore 获取数据时遇到问题。数据结构如下:
用户/{userId}/tests/{testType}/test_set/{testSetId}
我正在尝试检索特定测试类型的 test_set 集合中的所有文档。但是,即使 Firestore 中存在数据,我的查询也会返回空结果。 Firestore 安全规则设置为允许经过身份验证的用户进行读写访问。
users
└── {userId}
└── tests
└── {testType}
└── test_set
└── {testSetId}
├── correct_answers: int
├── total_questions: int
└── timestamp: Timestamp
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
这是我尝试获取数据的 Flutter 代码的相关部分:
Future<List<Map<String, dynamic>>> _fetchTestResults() async {
final user = FirebaseAuth.instance.currentUser;
if (user == null) return [];
print("UUID = " + user.uid);
// Build the reference step by step and print debug information
final usersRef = FirebaseFirestore.instance.collection('users');
print('Users reference path: ${usersRef.path}');
final userDocRef = usersRef.doc(user.uid);
print('User document reference path: ${userDocRef.path}');
final testsCollectionRef = userDocRef.collection('/tests/');
print('Tests collection reference path: ${testsCollectionRef.path}');
// final testResultsRef =
// testsCollectionRef.doc(testType).collection('test_set');
// print('Test results reference path: ${testResultsRef.path}');
// Fetch data
final snapshot = await testsCollectionRef.get();
print('Snapshot: ${snapshot.docs.length} documents');
if (snapshot.docs.isEmpty) {
print("Snapshot empty");
return [];
}
return snapshot.docs.map((doc) {
final data = doc.data();
print('Document ID: ${doc.id}, Data: $data');
return {
'test_id': doc.id,
'data': data,
'timestamp': data['timestamp'] as Timestamp,
'correct_answers': data['correct_answers'] as int,
};
}).toList();
}
但是如果我打印 userRef.get() 作为快照,我会得到如下输出
final snapshot = await usersRef.get();
print('Snapshot: ${snapshot.docs.length} documents');