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
            })
        }
    })
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM