For flutter while using firebase, how can you organize a collection by timetamp when embedded in a map and reading from a streambuilder

huangapple go评论68阅读模式
英文:

For flutter while using firebase, how can you organize a collection by timetamp when embedded in a map and reading from a streambuilder

问题

我正在尝试使用StreamBuilder来读取一系列消息(可能显示最近的5条),并希望按时间戳对它们进行组织。如您所见,这些文档属于不同的类别,最终会有几百个文档,以及集合,我不希望创建几百个集合(如果查看Firestore数据库,则为左侧集合,而不是我显示消息信息的右侧集合)。

我以以下方式向文档写入数据:

try {
    _firestore.collection('court_feed').doc('category3').set({
        '${DateTime.now().millisecondsSinceEpoch}': {
            'posterUID': '${user?.uid}',
            'posterDisplayName': user?.displayName,
            'content': postContent,
        }
    });
}

当从Firestore读取数据时,我有一个简单的流如下:

_firestore.collection('court_feed').doc(category3).snapshots()

如果使用FutureBuilder,我可以只获取整个文档,然后以这种方式组织映射,但这并不是很干净。

考虑到我想要按照所示的类别组织这些消息,我如何按时间组织所有这些消息呢?

英文:

I am trying to use a streambuilder to read a list of messages (maybe show the 5 most recent), and would like to organize them by timestamp. As you can see the documents are different categories, by the end there will be a few hundred documents, as well as collections and don't wish to make a few hundred collections (left side collection if looking at firestore database as opposed to right collection where I show the message info).

I am writing to the documents this way:

   try {
            _firestore.collection('court_feed').doc('category3').set({
            '${DateTime.now().millisecondsSinceEpoch}': {
            'posterUID': '${user?.uid}',
            'posterDisplayName': user?.displayName,
            'content': postContent,
        }

When reading from firestore I have a simple stream that looks like this:

_firestore.collection('court_feed').doc(category3).snapshots()

If using a futurebuilder I could just grab the entire document and organize the maps that way, its not very clean though.

Knowing that I would like to organize these by categories as shown, how can I organize all of these messages by time?

For flutter while using firebase, how can you organize a collection by timetamp when embedded in a map and reading from a streambuilder

答案1

得分: 2

根据您的数据库快照和您的代码片段,看起来您正在使用 Map 将消息存储在文档中,但使用${DateTime.now().millisecondsSinceEpoch}作为 Map 名称。

由于您当前的结构不会扩展,因为您将数据存储为文档中的嵌套数据

您当前的数据库结构也不会给您排序的结果,而是可以将文档保存为名为"messages"的子集合,并使用${DateTime.now().millisecondsSinceEpoch}作为文档 ID 来创建您的消息,类似于以下方式:

Firestore 数据库
└── court_feed - (集合)
    └── {category3} - 文档 ID
        └── messages - (子集合)
            ├── {DateTime.now().millisecondsSinceEpoch} - 文档 ID
            │   ├── posterUID:字符串
            │   ├── posterDisplayName:字符串
            │   └── content:字符串
            └── {DateTime.now().millisecondsSinceEpoch} - 文档 ID
                ├── posterUID:字符串
                ├── posterDisplayName:字符串
                └── content:字符串

使用这样的结构将帮助您按${DateTime.now().millisecondsSinceEpoch}的顺序获取文档,如下所示:

_firestore
    .collection('court_feed')
    .doc('category3')
    .collection('messages')
    .orderBy(FieldPath.documentId()) // 现在我们可以根据此字段排序
    .snapshots()

现在,要将新消息写入数据库,您可以按照以下代码片段进行操作:

var category = 'category3';
var documentId = DateTime.now().millisecondsSinceEpoch.toString();

_firestore
    .collection('court_feed')
    .doc(category)
    .collection('messages')
    .doc(documentId) // 设置新的文档 ID 为 DateTime.now().millisecondsSinceEpoch
    .set({
      'posterUID': '${user?.uid}',
      'posterDisplayName': user?.displayName,
      'content': postContent,
    })

参考:子集合

英文:

Based on your DB snapshot and your code snippet it looks like you are storing messages inside the documents using Map but using ${DateTime.now().millisecondsSinceEpoch} as a Map name.

As your current structure will not scale because you are storing data as Nested data in documents

Your current db structure will also not give you sorted result instead you can save the documents as an subcollection named messages and use ${DateTime.now().millisecondsSinceEpoch} as an document id to create your messages something like follows:

Firestore Database
└── court_feed - (Collection)
    └── {category3} - Document Id
        └── messages - (sub-collection)
            ├── {DateTime.now().millisecondsSinceEpoch} - Document Id
            │   ├── posterUID : string
            │   ├── posterDisplayName : string
            │   └── content : string
            └── {DateTime.now().millisecondsSinceEpoch} - Document Id
                ├── posterUID : string
                ├── posterDisplayName : string
                └── content : string

Using a structure like this will help you to get the documents order by ${DateTime.now().millisecondsSinceEpoch} as follows :

_firestore
    .collection('court_feed')
    .doc('category3')
    .collection('messages')
    .orderBy(FieldPath.documentId()) // 👈 we can order based on this now
    .snapshots()

Now to write the new message in the DB you can follow the following snippet :

var category = 'category3';
var documentId = DateTime.now().millisecondsSinceEpoch.toString();

_firestore
    .collection('court_feed')
    .doc(category)
    .collection('messages')
    .doc(documentId) // 👈 set a new document id as DateTime.now().millisecondsSinceEpoch
    .set({
      'posterUID': '${user?.uid}',
      'posterDisplayName': user?.displayName,
      'content': postContent,
    })

Reference : Subcollections

huangapple
  • 本文由 发表于 2023年6月22日 05:05:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定