wiljanslofstra / Jet-Chat

Meteor chat app, with multi-rooms and FB/Twitter login.
7 stars 1 forks source link

MessageList limit with $slice or other techniques #4

Open grigio opened 11 years ago

grigio commented 11 years ago

Hi, I'd like to limit the messages per chatroom to last 30 (example), do you know a proper way to do it?

I tried to do:

Messages.findOne({_id:'room6'}, {messages: { $slice: 5 }})
> Object {_id: "room6", messages: Array[28]}

but the $slice part seems to be ignored, even if in Mongo console the command below works:

db.messages.find({_id:'room6'}, {messages:{$slice: -5}} )

How would you manage the situation when the messages are too many per room? Thanks

wiljanslofstra commented 11 years ago

The problem is that findOne() only returns the object. And the find() method in your second example returns a cursor. The $slice function only works on cursors, so that's why your first line doesn't work properly. If you want to slice or limit the messages returned you have to convert the findOne() to an find(). :)

grigio commented 11 years ago

I've also tried with find instead of findOne but I alwais get the full array with messages :( I see from the docs that there are also skip and limit methods but I think they apply only to the root documents returned and not to limit the size of and array embedded in a document.

wiljanslofstra commented 11 years ago

Yes, i can't get it to work either... I guess the problem is in mini-mongo, that doesn't have all MongoDB capabilities yet. A workaround is to split it after you did the query, but it still does run the whole query and return all messages.

I think this is almost the same problem: http://stackoverflow.com/questions/10157454/meteor-cannot-observe-queries-with-skip-or-limit