I am writing a simple chat feature within my application. Given the fact some users will have multiple messages within a conversation, I need to provide reverse pagination so they can load previous messages when scrolling. From the model side, each message has a timestamp (a time interval) so that it's easy to query.
I'm able to query and order desc from the date field, however... the second I limit the response to X number of items.. somehow the date field is omitted and I get the first 5 in the collection, not the 5 I want ordered by date. How can I fix this?
Example
message one: 1
message two: 2
message three: 3
message four: 4
When I order desc, I get the right list [1,2,3,4,5]. When I limit(2), it gives me [1,2] but what I really want is [3, 4].
I am missing something obvious?
Update:
collection: "conversations". sub collection "messages".
Collection id is done by aggregating both user ids so it's easier to query a conversation of 2 users.
db.collection("conversations")
.document(identifier)
.collection("messages")
.order(by: "sentDate", descending: false)
.limit(to: 5)
.addSnapshotListener({ snapshot, error in
guard let document = snapshot else { return }
let messages = document.documents.map {
return Message.fromJSON($0.data())
}
observable.onNext(messages as! [Message])
observable.onCompleted()
})
If you are getting [1,2,3,4] during .order(by: "sentDate", descending: false) ,
and [1,2] when using .order(by: "sentDate", descending: false).limit(to: 2) , then you can do the following:
(ie. let messages = document.documents.reverse().map line in your code)
And you will get [3,4].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.