I’m creating a simple chat feature for a client’s app.
The chat itself is functioning, but I’m having a little trouble making the last message appear on the bottom part of the UI. Let me use a diagram to explain:
Let’s say that chat messages are A, B, C, D, consecutively. We want the app to look like this:
A
B
C
D
[text box]
Sounds good right?
Well here we have a problem. I want to limit the messages to the last say, 2 messages. I can do:
{limit: 2}
but that will result in this messages:
A
B
[text box]
As the collection limits to the last 2 elements, but not from the last. If we do:
.find({}, {limit:2, sort: {createdAt: -1}});
D
C
[text box]
Which shows the last 2 messages, but on the reverse order!
Probably what I’ll use if I can’t find another solution Just worried that this may be expensive, fetching the cursor everytime instead of iterating the cursor itself (actually not sure if it has any repercussions)
I think it has no downsides. Just tested rendering and it still only rerenders what has changed. The data is in the memory anyway. And with 2 documents it doesn’t matter anyway.
2 documents was just an example, I’d imagine this would be a whole lot (infinite scrolling chat) though I guess I’ll just worry about performance when i get there.