Show all posts created from specific year

294 views Asked by At

I created all the links to send a number with the specified year that the user wants to see. Now all I want to set the routes use that year and display the posts created that year. Basically the number that will go to the routes is for example 2001. What do I need to add here?

Routes

var keystone = require('keystone');
var async = require('async');

exports = module.exports = function(req, res) {

    var view = new keystone.View(req, res);
    var locals = res.locals;
    // This gets category spesified on link
    // and then use it to show
    // post from that category
    var val = req.url;
    var gc = val.substr(val.indexOf("&") + 1);

    // This gets Year spesified on link
    // and then use it to show
    // post from that year
    var gy = req.url;
    gy = gy.replace(/\D/g, '');
    gy = gy.substring(0, 4);

    // Init locals
    locals.section = 'exam_per_year';
    locals.filters = {
        category: req.params.category,
    };
    locals.data = {
        posts: [],
        categories: [],
    };
    // Load the posts
    view.on('init', function(next) {
        var c = keystone.list('PostCategory').model.findOne().where('key').equals(gc).exec(function(err, results) {
            if (err) {
                console.log(err);
            } else {
                var gcid = results._id;
                var q = keystone.list('Post').paginate({
                    page: req.query.page || 1,
                    perPage: 20,
                    maxPages: 100,
                }).where('state', 'published').where('categories').equals(gcid);
                q.exec(function(err, results) {
                    if (results && !err) {
                        locals.data.posts  = results.Array.map(function(curResult) {
                            return curResult.getFullYear() === gy; // Your year goes here
                        });
                        return next();
                    }
                // else { // You either have no posts or there was an error loading them}
                });
                // q.exec(function(err, results) {
                //  locals.data.posts = results;
                //  next(err);
                // });
            }
        });
    });
    // Render the view
    view.render('exam_per_year');
};

This is the model

var keystone = require('keystone');
var Types = keystone.Field.Types;

/**
 * Post Model
 * ==========
 */

var Post = new keystone.List('Post', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true },
});

Post.add({
    title: { type: String, required: true },
    categories: { type: Types.Relationship, ref: 'PostCategory', many: true },
    state: { type: Types.Select, options: 'draft, published, archived', default: 'published', index: true },
    publishedDate: { type: Types.Date, index: true, dependsOn: { state: 'published' } },
    image: { type: Types.CloudinaryImage },
    pronunciations: { type: Types.CloudinaryImage },
    answers: { type: Types.CloudinaryImage },
    content: {
        extended: { type: Types.Html, wysiwyg: true, height: 300 },
    },

});

Post.schema.virtual('content.full').get(function () {
    return this.content.extended || this.content.brief;
});

Post.defaultColumns = 'title, state|20%, author|20%, publishedDate|20%';
Post.register();

i already have the year on routes but i don't know how to use where correctly so far .where('publishedDate').equals('2001')it shows nothing heres a post in mongodb database from 1-1-2001

{"_id": ObjectID("5857b9387cf9b55946a5cae3"),
"slug": "test-exam-2001",
"title": "Test Exam 2001",
"state": "published",
"categories": [
    ObjectID("5857b80a7cf9b55946a5cadf")
],
"__v": 2,
"content": {
    "extended": "<p>empty</p>"
},
"publishedDate": ISODate("2000-12-31T22:00:00.000Z")}
2

There are 2 answers

0
Bill On BEST ANSWER

Here is how i got it working thanks to Shea Belsky and Jake Stockwin help

var keystone = require('keystone');
var async = require('async');

exports = module.exports = function(req, res) {
    var view = new keystone.View(req, res);
    var locals = res.locals;
    // This gets category spesified on link and then use it to show post from that category
    var val = req.url;
    var gc = val.substr(val.indexOf("&") + 1);
    // This gets Year spesified on link and then use it to show post from that year
    var gy = req.url;
    gy = gy.replace(/\D/g, '');
    gy = gy.substring(0, 4);
    // Init locals
    locals.section = 'exam_per_year';
    locals.filters = {
        category: req.params.category
    };
    locals.data = {
        posts: [],
        categories: []
    };
    // Load the posts
    view.on('init', function(next) {
        keystone.list('PostCategory').model.findOne().where('key').equals(gc).exec(function(err, results) {
            if (!err) {
                var gcid = results._id;
                var q = keystone.list('Post').paginate({
                        page: req.query.page || 1,
                        perPage: 40,
                        maxPages: 1,
                    })
                    .where('state', 'published').where('categories').equals(gcid);
                q.exec(function(err, results) {
                    var a = results.results.map(function(curResult) { //This will return only the spesified year
                        if (curResult.publishedDate.getFullYear() == gy) {
                            return curResult;
                        }
                    });
                    a = a.filter(function(element) { //This will remove every other post from the results
                        return element !== undefined;
                    });
                    locals.data.posts = a;
                    console.log(locals.data.posts);
                    next(err);
                });
            }
        });
    });
    // Render the view
    view.render('exam_per_year');
};
19
Shea Hunter Belsky On

publishedDate is of type Types.Date, and anything stored in that field is stored as a JavaScript Date object. Therefore, you need to go a little deeper in order to pull out all the posts from a certain year.

view.on('init', function (next) {
   var q = keystone.list('Post').paginate({
      page: req.query.page || 1,
      perPage: 200,
      maxPages: 100,
   }).where('state', 'published');
   q.exec(function (err, results) {
      if (results.length !== 0 && !err) {
         locals.yearPosts = results.map(function (curResult) {
            return curResult.getFullYear() === 2016; // Your year goes here
         });
         return next();
      }
      else {
         // You either have no posts or there was an error loading them
      }
   });
});

EDIT: Changed the condition to determine if you had any results.