0

我有一个 Keystone.js 博客,我想添加类似于 Wordpress /archive/year/month 的博客档案。我在帖子对象中添加了一些额外的日期字段,但我觉得有一种方法可以使用发布的日期来做到这一点。

现在存档年份只是“2014”,存档月份是“06”,而“-publishedDate”值将类似于"publishedDate" : Date( 1355644800000 ). 有没有办法在查询中编写一个函数来将日期解析为 JS 日期对象然后匹配值?

// Load the posts
view.on('init', function(next) {

    var q = keystone.list('Post').paginate({
            page: req.query.page || 1,
            perPage: 10,
            maxPages: 10
        })
        .where('state', 'published')
        .sort('-publishedDate')
        .populate('author categories');

    if (locals.data.category) {
        q.where('categories').in([locals.data.category]);
    }

            // If archive section, filter by year and month
            if (locals.data.archiveYear && locals.data.archiveMonth) {
        q.where('-publishedDate',locals.data.archiveYear);
                    q.where('-publishedDate',locals.data.archiveMonth);
    }

    q.exec(function(err, results) {
        locals.data.posts = results;
        next(err);
    });

});
4

2 回答 2

1

使用moment.js与 user1572796类似的代码

if (locals.filters.year) {
   var start = moment().year(locals.filters.year).month(locals.filters.month).startOf('month');
   var end = moment().year(locals.filters.year).month(locals.filters.month).endOf('month');

   q.where('publishedDate', { $gt: start, $lt: end });
}
于 2014-10-30T20:25:41.017 回答
0

这似乎有效:

    // Load the posts
view.on('init', function(next) {

    var q = keystone.list('Post').paginate({
            page: req.query.page || 1,
            perPage: 10,
            maxPages: 10
        })
        .where('state', 'published')
        .sort('-publishedDate')
        .populate('author categories');

    if (locals.data.category) {
        q.where('categories').in([locals.data.category]);
    }

function daysInMonth(month,year) {
  return new Date(year, month, 0).getDate();
}

if (locals.filters.year && locals.filters.month) {
  var postMonth = locals.filters.month - 1;
  var start = new Date(locals.filters.year, postMonth, 1);
  var end = new Date(locals.filters.year, postMonth, daysInMonth(locals.filters.month, locals.filters.year));
  q.find({publishedDate: { $gte: start, $lt: end }});
}

    q.exec(function(err, results) {
        locals.data.posts = results;
        next(err);
    });
于 2014-06-30T19:27:07.827 回答