0

I have a Keystone.js blog and I want to add blog archives similar to Wordpress /archive/year/month. I added some extra date fields to the post object but I feel there is a way to do this using the published date.

Right now archive year is just '2014' and archive month is '06', while the '-publishedDate' value would be something like "publishedDate" : Date( 1355644800000 ). Is there a way to write a function in the query to parse the date as a JS date object then match the values?

// 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);
    });

});
Scimonster
  • 32,893
  • 9
  • 77
  • 89
user1572796
  • 1,057
  • 2
  • 21
  • 46

2 Answers2

1

Using moment.js similar code than 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 });
}
0

This seems to work:

    // 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);
    });
user1572796
  • 1,057
  • 2
  • 21
  • 46