【问题标题】:Show all posts created from specific year显示从特定年份创建的所有帖子
【发布时间】:2017-01-03 18:09:59
【问题描述】:

我创建了所有链接以发送用户想要查看的指定年份的数字。现在我只想设置当年使用的路线并显示当年创建的帖子。基本上,将去路线的数字是例如 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();

我已经有一年的路线,但我不知道如何正确使用 where 到目前为止 .where('publishedDate').equals('2001') 它什么也没显示 这是 2001 年 1 月 1 日在 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")}

【问题讨论】:

    标签: node.js mongodb keystonejs


    【解决方案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');
    };
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • TypeError: results.map 不是函数
      • 所以现在这只是一个 JavaScript 问题,而不是与 keystone 有任何关系。 console.log(results)results.map 之前的输出是什么? IIRC,您只能在数组(方括号)而不是 json 对象(大括号)上调用 .map。无论如何,这个答案的重要部分是您需要在接收数据对象时调用.getFullYear
      • 我无法在此处从 console.log(results) 发布结果,因为它太长了,但我收到了 2 个包含所有信息的帖子,所以它在我尝试使用方括号的结果映射之前工作仍然没有工作
      • Keystone 查询的结果应该是一个数组,这就是Array.map 应该起作用的原因。可以console.log(typeof results)吗?或者您至少可以复制并粘贴console.log(results) 输出的部分结果(最好是开头或结尾)?
      • 所以,问题是您在模型上调用findOne 而不是find,因此只返回一个结果。如果您调用find 而不是findOne,那么结果将是一个数组,然后您可以执行results.map(不是results.Array.map)。
      猜你喜欢
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多