简体   繁体   中英

Searching Multiple parts of a Mongodb model

This is my search route:


router.get("/search", async (req, res)=>{
    let search = {}
    if(req.query.q !=null && req.query.q!==""){
        search.title = new RegExp(req.query.q, "i")
        search.description = new RegExp(req.query.q, "i") 
    }
    try{
        console.log(search)
        const posts = await Post.find(search)
        res.render("posts/search", {posts: posts, search: req.query})
    }catch(err){
        console.log(err)
    }
})

When I send my query like this, my console returns me this value:

{ description: /whateverIamsearchingfor/i, tags: /whateverIamsearchingfor/i }

And when I search only one of them and comment out the other line I get this: (no surprises)

{ description: /whateverIamsearchingfor/i}

Naturally, It works when only I search for either titles or descriptions. How do I fix this? I want to be able to make a search on both of these parts of this model at the same time. (or maybe even search the other parts as well)

Yay. I made it. In case anybody is still wondering how, I'll post it here:

const posts = await Post.find({ "$or": [
{ title: search.title }, 
{ description: search.description }
] });

Works like a charm now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM