Emmanuel Okocha
Emmanuel Okocha

Reputation: 397

How to use where to query the database using mongoose

I want to create an endpoint for the user to search for something, so im querying the database using where a particular row inlcudes the text the user has searched but $where keeps giving me an error that it is not a function

I have tried using the $where but to no avail

router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const search = await Course.find()
        search.$where(function () {
            return req.params.search_text.toLowerCase().includes(this.course_name.toLowerCase())
        })
        if (!search){
            return res.status(404).send({result: 'No Result found'})
        }

        res.status(200).send({result: search})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})

I want to be able to query the database for what the user has searched from a particular column (course_name) and return a response of the rows containing that at least three letters from the text the user searched

Upvotes: 1

Views: 100

Answers (2)

ganjim
ganjim

Reputation: 1416

You can directly use mongoDB $regex option in query to search your text:

router.get('/mobile/courses/search/:search_text', async(req, res)=>{
    try {
        const searchedItems = await Course.find({
            course_name: { 
                $regex: req.params.search_text,
                $options: 'i' // case insensitive
            } 
        })
        if (!searchedItems.length){
            return res.status(404).send({result: 'No Result found'})
        }
        res.status(200).send({result: searchedItems})
    }catch (e) {
        res.status(500).send({error: 'Unknown Error Occurred Try Again', codeerror: e.toString()})
    }
})

Upvotes: 1

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

First index the field that you want to search

Course.index({ course_name: 'text' });

Then use $regex

CourseModal
    .find({
        course_name: {
            $regex: searchString,
            $options: 'i'
        }
    })

Upvotes: 2

Related Questions