我希望找到上一篇文章。我知道我可以加载所有帖子并从那里检查..但这似乎数据很重。是否有更简洁的方式来查询上一篇文章?也许排序?或者有一种方法可以限制检索到的数据量...就像只有slug一样,以便减少数据量?
我只是想提出一个轻请求并找到下一篇文章。
这是我目前的解决方案
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');
}
答案 0 :(得分:3)
相应的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)
还有不同的其他方式来编写这些查询: - )
答案 1 :(得分:1)
您可以尝试检查在当前帖子之前发布的帖子:.where('publishedDate', { $lt: currentPost.publishedDate } )
,继续按publishedDate排序,然后拥有.limit(1)
。这应该使请求有点'更轻'