Using model.find () with LIKE in mongoose

0

I have a function here to search MongoDB using mongoose, but I would like it to find Brazil when I search for bra, Bra, Sil, sil, etc. I looked at the documentation and followed the example but it did not work, it does not return anything. Here is the code:

exports.postSearchCountry = (req, res, next) => {
        const countryName = req.body.countryName
        Country.find({
            name: /countryName/i
        })
        .then(countries => {
            res.render('country/countries', {
                countries: countries
            })
        })
        .catch(err => {
            console.log(err)
        })
    }
    
asked by anonymous 03.01.2019 / 19:40

1 answer

1

You are trying to use a regular expression to do the search, but it is not generating a regular expression dynamically. The expression /countryName/i will search for countries that literally contain "countryName" in their name, not that they contain the value of the countryName variable.

To generate a regular expression dynamically, use new RegExp(countryName, 'i') , that is

Country.find({
    name: new RegExp(countryName, 'i')
})

But I want to alert you that this is not the way to use regular expressions in Mongoose that I know, if that does not work, use

Country.find({
    name: { $regex: new RegExp(countryName), $options: 'i' }
})
    
03.01.2019 / 20:39