Node.js Mongoose:查找具有特定条件的文档
我正在编写一个新闻网站。我为某位作者/记者制作了一个特别的页面。此页面将包含他/她的所有帖子。以下是代码: 在app.js中Node.js Mongoose:查找具有特定条件的文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我正在编写一个新闻网站。我为某位作者/记者制作了一个特别的页面。此页面将包含他/她的所有帖子。以下是代码: 在app.js中 app.get("/author/:id", function(req,res) { //latest contains all posts Latest.find({author:"Richard Mann"}).sort([['_id', -1]]).exec(function(err,allLatest) { if(err)
app.get("/author/:id", function(req,res) { //latest contains all posts
Latest.find({author:"Richard Mann"}).sort([['_id', -1]]).exec(function(err,allLatest) {
if(err) {
console.log(err);
} else {
res.render("showAuthor", { latest : allLatest});
}
})
})
此代码有效,并显示特定作者的帖子。但如何为所有作者做到这一点(同时避免干代码)?查找指定作者的文档时应该应用什么条件?只需从客户端获取输入并将其传递给
find({author:req.params.id}
这将根据您从api/author/:id获得的id进行检查,并搜索任何指定的作者
app.get("/author/:id", function(req,res) { //latest contains all posts
Latest.find({author:req.params.id}).sort([['_id', -1]]).exec(function(err,allLatest) {
if(err) {
console.log(err);
} else {
res.render("showAuthor", { latest : allLatest});
}
})
})
如果你想按作者分组,你可以使用聚合器。非常感谢,它很有效!不知道为什么我没有想到这一点!不管怎样,你有没有可能知道这个问题:?当然我会看看。会让你知道的。你介意接受答案吗?对不起,我一定忘了接受答案,是吗!