1

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

1
  • i think you miss some basic knowledge about MongoDB. It is not a RDBMS and the concept of columns does not exists. Commented May 29, 2019 at 9:21

2 Answers 2

2

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'
        }
    })
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.