Kotlin-Jetpack Compose中Firestore查询无返回结果问题排查
Kotlin Jetpack Compose中Firestore查询无结果问题排查
问题描述
在Kotlin-Jetpack Compose项目中使用Firestore查询时遇到无结果返回的问题,已传入硬编码的字符串参数,但始终无法获取预期数据。
初始化函数代码
@HiltViewModel class WordsViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val words_coursesService: Words_CoursesService, logService: LogService ) : LearningEnglishAppViewModel(logService){ var words = mutableStateListOf<Words>() init { viewModelScope.launch { val wordsList = words_coursesService.getWordsFromCourses("08IZV3EvqKKPw7z85Sdr") words.clear() words.addAll(wordsList.filterNotNull()) } resetGame() } }
查询函数代码
override suspend fun getWordsFromCourses(coursesId: String): List<Words?> { val wordsCoursesQuery = firestore.collection(WORDS_COURSES_COLLECTION) .whereEqualTo(COURSES_ID_FIELD, coursesId) .get() .await() val listWordsCourses = wordsCoursesQuery.toObjects<Words_Courses>() val listWords = mutableListOf<Words?>() for (wordsCourses in listWordsCourses) { val wordsDocument = firestore.collection(WORDS_COLLECTION) .document(wordsCourses.wordsId) .get() .await() val words = wordsDocument.toObject<Words>() listWords.add(words) } return listWords }
Firestore数据说明
Firestore中words_courses集合存在coursesId值为08IZV3EvqKKPw7z85Sdr的文档,且文档包含有效的wordsId字段,关联到words集合中的对应文档。
排查建议
- 验证字段与集合名匹配:确认
WORDS_COURSES_COLLECTION、COURSES_ID_FIELD、WORDS_COLLECTION这些常量的字符串值,和Firestore后台的集合名、字段名完全一致(Firestore对大小写敏感)。 - 检查安全规则权限:确保Firestore的安全规则允许当前用户读取
words_courses和words集合的数据,避免因权限限制导致查询无返回。 - 添加调试日志:在查询函数中加入日志输出:
- 打印
wordsCoursesQuery.size(),确认是否从words_courses集合查询到了文档; - 打印
wordsCourses.wordsId,检查是否正确获取到关联的单词ID; - 打印
wordsDocument.exists(),验证对应的words文档是否存在。
- 打印
- 检查数据模型映射:核对
Words_Courses和Words数据类的字段名、数据类型,是否与Firestore文档中的字段完全匹配,避免因映射错误导致数据无法解析。 - 调整协程执行顺序:
resetGame()在init块中同步执行,若该函数依赖words数据,可能会在查询完成前执行。可将resetGame()移到协程内words.addAll之后,确保数据加载完成后再执行。
内容的提问来源于stack exchange,提问作者TranDatK
相关产品推荐
相关产品推荐

