问题:我从 firestore 收到的帖子项目的顺序与我传递给 firestore 获取的帖子项目的顺序不同。
这是用户的简化数据结构,帖子看起来像这样。
/root
/users (collection)
/user_id_a (document with fields)
- user_id_a
- user_name_aa
- bookmark_list
/user_id_b (document with fields)
- user_id_b
- user_name_aa
- bookmark_list
/posts (collection)
/post_id_c (document with fields)
- post_id_c
- post_title
- posted_by
- created_at
/post_id_d (document with fields)
- post_id_d
- post_title
- posted_by
- created_at
我想要实现的是用这个数据结构添加书签功能。 我现在可以收集用户想要在用户文档中的
post_id
字段中保存为书签的 bookmark_list
。当用户想要在屏幕上查看书签列表时,将调用下面的代码。 (使用黑暗语言)
await _firebaseFirestore
.collection(_pathPosts)
.where(FieldPath.documentId, whereIn: userProfileModel.bookmarkList)
.withConverter(
fromFirestore: PartiesPostModel.fromFirestore,
toFirestore: (PartiesPostModel value, _) => value.toJson(),
)
.get()
.then(
(QuerySnapshot<PartiesPostModel> querySnapshot) {
logger.i("bookmark list successfully fetched");
List<PartiesPostModel> l = [];
for (var docSnapshot in querySnapshot.docs) {
l.add(docSnapshot.data());
}
return l;
},
onError: (e) {
logger.e("Error completing: $e");
return List.empty();
}
因为我在
post_id
中传递 userProfileModel.bookmarkList
列表,并且 post_id
是由 firestore 在收集时生成的字母随机组合,当获取完成后,它们的顺序是使用 documentId 按 firestore 的 default way 排序的不管我传递的 post_id
中 userProfileModel.bookmarkList
的顺序如何。有什么方法可以按照书签项目在 userProfileModel.bookmarkList
中的顺序获取这些帖子文档,而不是按照 documentId 的 firestore 顺序?
如果您提出任何其他建议以使其发挥作用,我也将不胜感激。查询的
where
条件控制返回哪些文档,但不控制返回它们的顺序。
控制 Firestore 返回文档顺序的唯一方法是使用
orderBy
语句。如果您无法用 orderBy
表达您的要求(似乎是这种情况),您将需要在应用程序代码中对结果重新排序。由于 querySnapshot.docs
包含所有文档及其数据,因此这应该非常简单 - 并且(更重要的是)几乎不需要时间。