2017-03-23 63 views
1

我正在編寫一個新聞網站。我爲特定的作者/記者撰寫了專門的頁面。該頁面將包含他所有的職位/她。這裏的代碼:貓鼬:查找特定條件的文檔

在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) { 
      console.log(err); 
     } else { 
      res.render("showAuthor", { latest : allLatest}); 
     } 
    }) 
}) 

此代碼的工作,並通過特定作者的帖子出現。但如何爲所有作者做到這一點(同時避免DRY代碼)?在爲特定作者查找文檔時應該適用什麼條件?

+0

如果您想通過'author'進行分組,您可以使用['$ group'](https://docs.mongodb.com/manual/reference/operator/aggregation/group/)聚合器。 – luisenrike

回答

1

就拿從客戶端的輸入,並把它傳遞給find({author:req.params.id}這將檢查ID的基地,你會從你的API /作家/獲取:身份證,讓你搜索任何指定的作者

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}); 
      } 
     }) 
    }) 
+0

非常感謝,它工作!不知道爲什麼我沒有想到這個!無論如何,任何機會,你會知道這個問題:http://stackoverflow.com/questions/43015578/authorization-in-node-js? – eknoor4197

+0

當然,我會看看它。會讓你知道 。你介意接受答案嗎? –

+0

對不起,我一定忘了接受答案,做到了! – eknoor4197