首页 > 解决方案 > 猫鼬部分搜索

问题描述

我正在尝试从集合字段 property_address 中搜索位置。它包含诸如 SouthEx、New delhi 之类的值。如果我搜索 southEx , New delhi,Delhi,India ,它将显示包含 southEx,New Delhi 的结果。

我们将如何使用猫鼬搜索来做到这一点?

标签: node.jsmongodbmongoosemongodb-query

解决方案


形式:

<form method="GET">
  <input type="text" name="q" id="q"/>
</form>

对输入文本的 keyup 的 Ajax 请求

<script>
$(document).on('keyup','#q',function(){
   if($(this).val()!=='' || $(this).val!=undefined){
      var query=$(this).val();
      $.ajax({
         url:'http://localhost:3000/search?q='+ query,
         type:'GET',
         dataType:'json',
         success:function(response){
              console.log(response);
              if(response.status=='ok'){
                 console.log(response.search_results);
              }
          },
         error:function(){
             alert('Failed to search address');
         } 
      });
   }
});
</script>

服务器.js

app.get('/search',function(req,res) {

 if(req.query && req.query.q) {

     var q = req.query.q;

     YourModel.find({"property_address": new RegExp('^'+q+'$', "i")}, function(err, data) {
   if(!err && data) {
     return res.json({status:'ok',search_results:data});
   }
});
} else {
     return res.json({status:'error',message:'No input'});
}
});

推荐阅读