2014-06-28 67 views
0

我有一個Keystone.js博客,我想添加類似於Wordpress/archive/year/month的博客檔案。我爲post對象添加了一些額外的日期字段,但我覺得有一種方法可以使用發佈的日期來完成此操作。在mongodb中查詢JavaScript日期對象

現在歸檔年份僅爲'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); 
    }); 

}); 

回答

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