2017-08-27 18 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包。