Using model.find() with LIKE in Mongoose

Asked

Viewed 900 times

2

I have a function here to do a search on Mongodb using Mongoose, but I would like him to find Brazil when I searched for bra, Bra, Sil, Sil, etc. I looked in the documentation and followed the example but it did not work, it does not return anything. Follows 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)
        })
    }

1 answer

2


You are trying to use a regular expression to do the research, but you are not generating a dynamically regular expression. The expression /countryName/i will search for countries that literally contain "countryName" on their behalf, not containing the value of the countryName variable.

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

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

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

Country.find({
    name: { $regex: new RegExp(countryName), $options: 'i' }
})
  • Thank you. In the example of the documentation of Mongoose they use a direct string, so it was not necessary to use the new Regexp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.