1

我一直在窗口上添加消息,但我只想显示最后 10 条消息。我该怎么做?在 jQuery 中,我可以使用 append 和 remove 到列表中,但在 Meteor 中我有这样的东西。

在 HTML 中

<template name="messages">
    {{#each messages}}
       <strong>{{name}}</strong> : {{message}}<br>
    {{/each}}
</template>

我正在遍历消息,这使我的应用程序显示所有消息。那么我如何选择仅有的 10 个,而不是循环遍历整个。谢谢!

 Template.messages.messages = function () {
     return Messages.find({}, { sort: { time: -1 }});
 }

 Template.input_box.events = {
     "keydown input#message" : function(event){
         if (event.which == 13) { 
        if (Meteor.user())
        {
            var name = Meteor.user().profile.name;
        }
        else
        {
            var name = "Anonymous";
        }

        var message = document.getElementById("message");

        var thetime = new Date();
        var time_string = "time "+thetime.getHours();
        if (message.value != "") {
            Messages.insert({
                name: name,
                message: message.value,
                time: time_string,
            });

            document.getElementById("message").value = "";
            message.value = "";
        }
    }
   }

}

4

1 回答 1

1

If you're not going to display the messages, I would go even further and take them off the client's minimongo completely. Otherwise it will just fill up a cache you aren't using and pollute the merge box. The following publication will make all messages but the last 10 disappear on the client automatically:

Meteor.publish("messages", function() {
    return Messages.find({}, {
        sort: { time: -1 },
        limit: 10
    });
});

A few notes:

  • You should compute timestamps on the server because client timestamps are unreliable and messages won't necessarily appear in the order they were sent. Add a deny hook or use collection-hooks.
  • You may need to sort the messages again on the client in ascending order of timestamp, unless you are displaying them newest-first.
  • Make sure you have appropriate indexes on your Mongo collection (especially on the time field) so that the server can efficiently track the last 10 messages.

    Messages._ensureIndex({time: 1});
    

    plus whatever other fields you are using. Consult http://docs.mongodb.org/manual/core/indexes/ for proper ordering if you are using compound indexes.

于 2013-09-19T16:36:15.917 回答