我需要有人帮助我解决这个问题,所以我的数据库中每个类别都有几篇博客文章,但我只想在索引 View 上显示每个类别中的一篇博客文章(我正在使用 ejs),我该如何实现这一点?我是 node.js 和 mongoose 的新手。请哪位兄弟帮帮忙。谢谢!
我已在下面发布了我的 app.js 和 index.ejs 文件。
app.get("/index", function(req, res, next){
output = {
sports: [],
fashion: [],
food: [],
headlines: [],
};
async.parallel([
function(cb){
Blog.find({"category": "sports"}).sort({"created": -1}).exec(function(err, sportsBlogs){
if (err){
console.log(err);
} else {
output.sport = sportsBlogs;
cb(null, sportsBlogs);
}
});
},
function(cb) {
Blog.find({"category": "fashion"}).sort({"created": -1}).exec(function(err, fashionBlogs){
if (err){
console.log(err);
} else {
output.fashion = fashionBlogs;
cb(null, fashionBlogs);
}
});
},
function(cb) {
Blog.find({"category": "food"}).sort({"created": -1}).exec(function(err, foodBlogs){
if (err){
console.log(err);
} else {
output.food = foodBlogs;
cb(null, foodBlogs);
}
});
},
function(cb) {
Blog.find({"category": "headlines"}).sort({"created": -1}).exec(function(err, headlinesBlogs){
if (err){
console.log(err);
} else {
output.headlines = headlinesBlogs;
cb(null, headlinesBlogs);
}
});
}
], function(err, results){
res.render("index", {
sportsBlogs: output.sports,
fashionBlogs: output.fashion,
foodBlogs: output.food,
headlinesBlogs: output.headlines
});
});
});
<% headlinesBlogs.forEach(function(blog){ %>
<div class="col span-2-of-3 headlines-story-container">
<img class="headline-image" src="<%= blog.storyImage %>">
<p class="hs-category"><a href="/index"><%=blog.category%></a></p>
<h3 class="hs-title"><a href="/index"><%=blog.title%></a></h3>
<p class="hs-story-intro"><%= blog.body.substring(0, 200) %>... <a href="/index/<%= blog._id %>">Continue Reading</a></p>
<div class="col span-1-of-2 hs-author-box">
<a href="/"><img src="<%=blog.authorImage %>"></a>
</div>
<div class="col span-1-of-2 hs-author-text">
<h5 class="hs-author"><a href="/index">By <%=blog.author%></a></h5>
</div>
</div>
<% }); %>
最佳答案
要仅获取一篇博客文章,请使用 .findOne()
而不是.find()
,因为它返回 Object
而不是Array
的Objects
, .forEach()
行不通。
所以替换 Blog.find()
与 Blog.findOne()
并删除 .forEach()
行:
这个<% headlinesBlogs.forEach(function(blog){ %>
最后一个<% }); %>
并使用headLineBlogs
直接点赞
<p class="hs-category"><a href="/index"><%=headlinesBlogs.category%></a></p>
您应该考虑将变量重命名为单数并删除 s
因为这是一篇文章。
关于javascript - 如何查询 Mongoose 数据库以检索一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601164/