2015-03-13 52 views
0

用戶在我的網站上分享帖子,每篇文章都有一個城市和類別以及投票選項。我在頂部有一個菜單幫助用戶過濾城市,類別,頂級投票和最新的帖子。我正試圖做的是:連接的MongoDB查詢

  • 如果用戶更改城市,那麼我將返回該城市的所有帖子。
  • 如果此用戶也更改類別。以及我必須返回該類別的帖子,但也是該城市。
  • 如果用戶選擇了最新版本,我必須返回該城市中該類別的最新帖子。
  • 而我在城市名單中有一個特殊選項。哪些應該在所有城市中返回帖子。並在類別列表中。

我使用流星&落得這樣做麪條:

if (Session.get('topPosts')){ 
    if(Session.get("selectedCity") && Session.get("selectedCategory")){ 
     if (Session.get("selectedCity") === Cities[0] && Session.get("selectedCategory") === Categories[0]){ 
      return Posts.find({}, {sort: {score: -1}}); 
     } 
     else if (Session.get("selectedCity") === Cities[0]){ 
      return Posts.find({ category: Session.get("selectedCategory") }, {sort: {score: -1}}); 
     } 
     else if (Session.get("selectedCategory") === Categories[0]){ 
      return Posts.find({ city: Session.get("selectedCity") }, {sort: {score: -1}}); 
     } 
     return Posts.find({ city: Session.get("selectedCity"), category: Session.get("selectedCategory") }, {sort: {score: -1}}); 
    } 
    .. 

我是新來的MongoDB。我不知道是否可以通過簡單查詢或多個查詢之間的組合來實現此目的。

回答

1

您可以組合一組搜索和排序參數,並在最後應用它們,而不是對每個搜索可能性都有不同的查詢。

var selector = {}; 
var sort = {}; 
if (Session.get('selectedCity') selector.city = Session.get('selectedCity'); 
if (Session.get('selectedCategory') selector.category = Session.get('selectedCategory'); 
if (Session.get('topPosts') sort = {sort: {score: -1}}; 
return Posts.find(selector, sort); 

我會讓你找出如何做你的特殊城市選項。