我在找上一篇文章。我知道我可以把所有的帖子都装进去然后从那里查…但数据似乎很重。有没有一种更简洁的方法来查询上一篇文章?也许是分类?或者也许有一种方法可以限制检索的数据量。只喜欢鼻涕虫这样它就不那么重数据了?
我只是想提出一个简单的要求,并找到下一个职位。
这是我目前的解决方案

var keystone = require('keystone');

exports = module.exports = function(req, res) {
    var view = new keystone.View(req, res),
        locals = res.locals;

    // Set locals
    locals.section = 'news';
    locals.filters = {
        post: req.params.post
    }
    locals.data = {
        previousPost: []
    }

    // Load the current post
    view.on('init', function(next) {

        var q = keystone.list('Post').model.findOne({
            state: 'published',
            slug: locals.filters.post
        }).populate('author categories');

        q.exec(function(err, result) {
            locals.data.post = result;
            next(err);
        });

    });

    // Load previous post
    view.on('init', function(next) {
        var q = keystone.list('Post').model.find().where('state', 'published').sort('-publishedDate');
        q.exec(function(err, results) {
            allPosts = results;
            for (var i = 0; i < allPosts.length; i++) {
                if (allPosts[i]["slug"] === locals.filters.post) {
                    locals.data.previousPost = allPosts[i+1];
                    next(err);
                }
            }
        });
    });

    // Render the view
    view.render('post');
}

最佳答案

相应的mongo查询是:
db.posts.find({state: "published", publishedDate: {$lt: currentpost.publishedDate}}).sort({publishedDate: -1}).limit(1)
我认为对应的keystone/mongoose查询是:
var q = keystone.list('Post').model.find({state: "published", publishedDate: {$lt: currentpost.publishedDate}}).sort('-publishedDate').limit(1);
如果只想选择文章的标题,则可以添加选择查询筛选器:
var q = keystone.list('Post').model.find({state: "published", publishedDate: {$lt: currentpost.publishedDate}}).sort('-publishedDate').select('title').limit(1);
等效的mongo查询如下:
db.posts.find({state: "published", publishedDate: {$lt: currentpost.publishedDate}},{title: 1}).sort({publishedDate: -1}).limit(1)
还有其他不同的方法来编写这些查询:-)

07-24 09:31