Reverse MeteorJS collection

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!

What is the best way to do this?

Don’t know much mongo, but from quick read of the doco you can do

db.collection.find().sort({createdAt: -1}).limit(2)

So it’ll reverse and take top 2.

Just tried it, unfortunately it doesn’t seem to work -> what’s returned by the Meteor find method is a custom cursor different from MongoDB.

.find({}, {limit:2, sort: {createdAt: -1}}).fetch().reverse();

maybe.

Probably what I’ll use if I can’t find another solution :slight_smile: 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.

1 Like

I am addicted to piping helpers. So for me it would be something like

{{ #each myOwnReverseHelper findHelper }} :smiley:

1 Like

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.

Thanks @Sanjo!