我试图用角度2在meteor中进行全文搜索。有我的发布功能:
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 :(得分:0)
Nutrition.find({}).subscribe(data=>{ console.log(data.length); });
这很糟糕:删除它。在Blaze助手中调用Nutrition.find({})
,或者使用适用于Meteor的Angular / React集成来读取绑定到数据的适当方法。
要解决您的具体问题,您需要删除旧订阅。
var sub = null;
public searchProducts = _.debounce((query) => {
if (!!sub) {
sub.stop();
}
sub = Meteor.subscribe('search', query);
}
这会导致闪烁行为,这是一个不同的问题。您应该扩展Nutrition.find({})
以过滤查询的某些部分。
在生产设置中,我实际上使用服务器端的发布句柄创建一个合成字段,指示哪些字段满足哪个查询。根据您的需要,这可能过度设计(太难以正确实施)。