Reverse MeteorJS collection


#1

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?


#2

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.


#3

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.


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

maybe.


#5

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)


#6

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.


#7

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

{{ #each myOwnReverseHelper findHelper }} :smiley:


#8

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!