gpt4 book ai didi

mongodb - 我如何使用 meteor 实时搜索一个集合,并且只显示匹配的结果?

转载 作者:可可西里 更新时间:2023-11-01 09:55:37 26 4
gpt4 key购买 nike

我正在尝试创建一个搜索,该搜索将过滤项目数据库并在搜索输入下方显示匹配选项,以便用户可以按原样选择“有效”选项。我得到了过滤项目的效果。但是,当搜索栏为空时,它会显示该集合中的所有项目。有什么方法可以防止这种情况发生,以便它仅在搜索开始后显示选项?

HTML

<template name="addItem">
<form class="addNewItem">
<input type="text" class="newItem" name="newItem" placeholder=" + new item">
</form>
<ul>&nbsp;
{{> search}}
</ul>
</template>

<template name="search">
&nbsp;
{{#if searchResults.results}}
{{#each searchResults.results}}
<li>
{{itemName}}
</li>
{{/each}}
{{/if}}
</template>

JS

'keyup input.newItem': function (evt) {
Session.set('search-query', evt.currentTarget.value);
var search = Session.get('search-query');
console.log(search);
},

});

Template.search.helpers({
searchResults: function (){
var keyword = Session.get('search-query');
var query = new RegExp( keyword, 'i' );
var results = Equipment.find({'itemName': query}, {});
return {results: results};
}
});

最佳答案

在模板中添加一个 if block :

<template name="addItem">
<form class="addNewItem">
<input type="text" class="newItem" name="newItem" placeholder=" + new item">
</form>
<ul>&nbsp;
{{#if searchInputNotEmpty}}
{{> search}}
{{/if}}
</ul>
</template>

并添加一个 searchInputNotEmpty 帮助程序,以检查您已经设置的 search-query session 变量:

Template.addItem.helpers({
searchInputNotEmpty: function() {
var input = Session.get('search-query');
return input != null && input != '';
}
});

关于mongodb - 我如何使用 meteor 实时搜索一个集合,并且只显示匹配的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com