net.user
net.user

Reputation: 831

how to use meteors collection.find() together with sort, skip and limit

I'm writing a chat program using Meteor. I need to show the 10 most recent messages in ascending order.

Messages.find({...}, {sort: {created: 1}, skip: getMessageCount()-10, limit: 10});

This code shows me only the first 10 messages.

Does the skip parameter work in Meteor and I made a mistake, or are there any known bugs?

Upvotes: 3

Views: 3858

Answers (2)

Konstantin Victorov
Konstantin Victorov

Reputation: 177

You just need to form on a server

Messages.find({...}, {sort: {created: -1}, limit: 10});

And then on a client

Messages.find({...}, {sort: {created: 1}})

What here will happen:

  1. You get from Mongo a splitting of 10 last messages but in a wrong order
  2. You run formatting the right order on a client

Upvotes: 1

sohel khalifa
sohel khalifa

Reputation: 5578

The reason why it returns first 10 messages is: {sort: {created: 1}} , which return in ascending order of the value created attribute.

You should write {sort: {created: -1}}, ie. records with higher value of created will be returned first.

Also, assuming that the created carries a valid date value along with the timestamp, you should insert its parsed value, in order to efficiently perform sorting based on date.

Upvotes: 2

Related Questions