2017-08-27 27 views
0

林試圖在與角2流星全文檢索,這正是我發佈FUNC:流星全文搜索。在客戶認購後,收集包含舊的搜索結果

Meteor.publish("search", (searchValue) => { 
 
    console.log(searchValue); 
 
    if (searchValue) { 
 
     return Nutrition.find(
 
      {$text: {$search: searchValue}}, 
 
      { 
 
       // `fields` is where we can add MongoDB projections. Here we're causing 
 
       // each document published to include a property named `score`, which 
 
       // contains the document's search rank, a numerical value, with more 
 
       // relevant documents having a higher score. 
 
       fields: { 
 
        'name.long': 1, 
 
        score: {$meta: "textScore"} 
 
       }, 
 
       // This indicates that we wish the publication to be sorted by the 
 
       // `score` property specified in the projection fields above. 
 
       sort: { 
 
        score: {$meta: "textScore"}, 
 
       }, 
 
       limit: 20 
 
      } 
 
     ); 
 
    } else { 
 
     return Nutrition.find({}) 
 
    } 
 
});

和客戶端:

public searchProducts = _.debounce((query) => { 
 
     Meteor.subscribe('search', query); 
 
     Nutrition.find({}).subscribe(data=>{ 
 
      console.log(data.length); 
 
     }); 
 
    }, 500);

,但在每個訂閱集合包含新值(來自實際搜索)和舊值(來自舊搜索)之後。

這是什麼原因?我能做些什麼來避免這種情況?

回答

0
Nutrition.find({}).subscribe(data=>{ 
     console.log(data.length); 
    }); 

這是很糟糕的:將其刪除。在Blaze helper中調用Nutrition.find({}),或者閱讀使用適用於流星的Angular/React集成的數據綁定方法。

要解決您的特定問題,您需要拆除舊的訂閱。

var sub = null; 
public searchProducts = _.debounce((query) => { 
    if (!!sub) { 
     sub.stop(); 
    } 
    sub = Meteor.subscribe('search', query); 
} 

這將導致閃爍的行爲,這是一個不同的問題。您應該擴展您的Nutrition.find({})以篩選部分查詢。

在生產設置中,我實際上使用服務器端的發佈句柄創建了一個合成字段,用於指示哪些字段滿足哪個查詢。這可能過度設計(對於正確實施而言太具有挑戰性)以滿足您的需求。我想推薦https://atmospherejs.com/easy/search包。