显示从特定年份创建的所有帖子

时间:2016-12-21 17:43:26

标签: node.js mongodb keystonejs

我创建了所有链接,用于发送用户想要查看的指定年份的数字。现在,我想设置路线使用那一年并显示当年创建的帖子。基本上,路线的数量是例如2001年。我需要在这里添加什么?

路线

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

这是模型

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

我已经有了一年的路线,但我不知道如何正确使用 到目前为止。(' publishedDate')。equals(' 2001')它什么都没有显示 继承了1-1-2001的mongodb数据库中的帖子

{"_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 个答案:

答案 0 :(得分:1)

感谢Shea Belsky和Jake Stockwin帮助

,以下是我的工作方式
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');
};

答案 1 :(得分:0)

publishedDate的类型为Types.Date,存储在该字段中的所有内容都存储为JavaScript Date对象。因此,您需要更深入一些,以便从特定年份中提取所有帖子。

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

编辑:更改条件以确定您是否有任何结果。