如何按插入时间对 Meteor 集合进行排序? [英] How can I sort a Meteor collection by time of insertion?

查看:23
本文介绍了如何按插入时间对 Meteor 集合进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Meteor 进行我的第一个项目,但在排序方面遇到了一些困难.

I am working on my first project using Meteor, and am having some difficulty with sorting.

我有一个表单,用户可以在其中输入格言,然后将格言显示在列表中.目前最新的格言会自动显示在列表底部.有没有一种简单的方法可以让最新出现在列表顶部?

I have a form where users enter aphorisms that are then displayed in a list. Currently the most recent aphorisms automatically display at the bottom of the list. Is there an easy way to have the most recent appear at the top of the list instead?

我试过了:

   Template.list.aphorisms = function () {
    return Aphorisms.find({}, {sort: {$natural:1}});
};

我很难过,因为 Meteor 文档没有很多例子.

And am stumped because the Meteor docs don't have many examples.

推荐答案

假设 date_created 与时间戳一起采用有效的日期格式,您应该插入 date_created 的解析值 使用 Date.parse() javascript 函数,它给出了 1970 年 1 月 1 日和 date_created 中包含的日期值之间的毫秒数.

Assuming that the date_created is in a valid date format along with the timestamp, You should insert the parsed value of date_created using Date.parse() javascript function, which gives the number of milliseconds between January 1, 1970 and date value contained in date_created.

因此,最近添加的记录将包含比之前插入的记录更大的 date_created 值.

As a result of that, the most recently added record will contain greater value of date_created than the record inserted before it.

现在在获取记录时,按照 date_created 参数的降序对游标进行排序:

Now when fetching the records, sort the cursor in descending order of the date_created parameter as:

 Aphorisms.find({}, {sort: {date_created: -1}});

这会将记录从新到旧排序.

This will sort records from newer to older.

希望这会有所帮助.

这篇关于如何按插入时间对 Meteor 集合进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆