mongoose模糊查询

模糊查询要用到 $or 和 $regex

前端请求:

search(){
        let searchV=$.trim($("#searchV").val());
        if(searchV.length<1){
          alert("请输入关键字进行搜索");
          return;
        }
        $.ajax({
          url:"http://localhost:3000/search/"+searchV,
          success:res=>{
            console.log("查询的数据",res)
            if(res.data.length>0){
              this.isSearch=true
              this.searchValue=res.data
            }
          },
          error:err=>{
            console.log(err)
          }
        })

      }

express后端代码:

// 根据模糊信息查询简讯
app.get("/search/:searchV",(req,res)=>{
    let regexp=new RegExp(req.params.searchV,'i')
    
    randomArt.find({$or:[{title:{$regex:regexp}},{content:{$regex:regexp}},{author:{$regex:regexp}}]},(err,doc)=>{
        if(err){
            console.log(err)
            res.send({
                code:400,
                msg:"查询失败"
            })
        }
        if(doc){
            res.send({
                code:200,
                msg:"查询成功",
                data:doc
            })
        }
    })
})
原文地址:https://www.cnblogs.com/shanchui/p/13066076.html