如何查询mongodb以获取即将过期的信用卡列表?

时间:2014-11-21 20:37:27

标签: mongodb date meteor momentjs

我的收藏品中有卡片作为包含每张卡片的子文档阵列的文件。每张卡都是一个有很多键的对象。到期的两个密钥是expiration_month和expiration_year。

这是一个例子。

{
    _id: '1',
    card: [
        {
            'expiration_month': 10,
            'expiration_year': 2017
        },
        {
            'expiration_month': 01,
            'expiration_year': 2015
        },
    ]
}

如何将正确的列表发布到此路由的订阅中,以便我可以使用每个循环来获取正确的列表?我只想获得任何在未来三个月内过期的卡片。

{{#each expiring_cards}}
    {{> ExpiringCards}}
{{/each}}   

Meteor.publish('card_expiring', function () {
    var before_date = moment(new Date()).add(3, 'month');
    return Donate.find( { moment(new Date('card[0].expiration_year' + '/' + 'card[0].expiration_month'))._d : { $lte: before_date} });
});

我知道上面的发布代码不起作用,我怎么能改变它才能使它工作,或者有更好的方法吗?

由于

1 个答案:

答案 0 :(得分:0)

最简单的方法似乎是将这两个字段连接到Date对象,然后运行以下查询。

How to combine the two fields - answer here

Meteor.publish('card_expiring', function () {
    var today = new Date();
    var future_date = new Date(new Date(today).setMonth(today.getMonth()+3));
    return Donate.find({'card.expires' : {$lte : future_date }}, { card : true } );
});

当然,这只会让我获得与此查询匹配的任何卡子文档,这意味着将包含不匹配的卡,但这些卡位于子文档中。

为了进一步过滤我在帮助器中使用了这个。

Template.ListExpiringCards.helpers({
    list: function () {    
    //The subscription filters out the records with subdocument card, 
    //which contain cards expiring in the next 3 months
        return Donate.find(); 
    },
    expiring_cards: function () {
    //This further filters only to the cards that match the above criteria
    // then returns an array to the Meteor template for the each loop
        var returnThisValue = [];
        this.card.forEach(function(entry) {
            var today = new Date();
            var future_date = new Date(new Date(today).setMonth(today.getMonth()+3));
            if (entry.expires <= future_date) {
                returnThisValue.push(entry);
            }
        });
        return returnThisValue;
    }
});

这在我的模板中

{{#each list}}
    {{#each expiring_cards}}
        {{> ExpiringCards}}
    {{/each}}
{{/each}}