gpt4 book ai didi

javascript - 高效地查找以前的帖子(keystoneJS)

转载 作者:可可西里 更新时间:2023-11-01 10:00:31 24 4
gpt4 key购买 nike

我正在寻找以前的帖子。我知道我可以加载所有帖子并从那里检查..但这似乎数据量很大。有没有更简洁的方法来查询上一篇文章?也许有排序?或者也许有一种方法可以限制检索到的数据量.. 就像 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');
}

最佳答案

对应的mongo查询为:
db.posts.find({state: "published", 发布日期: {$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)

还有其他不同的方式来编写这些查询:-)

关于javascript - 高效地查找以前的帖子(keystoneJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com