0

How would I search for queries in MongoDB (using the mongoose library) without them being case sensitive?

Lets say I have a query that has the string data of Adam. That query is case sensitive, so searching for that query as adam will return a null.

I tried using regex, and disabling the case sensitivity with it. It did the job, but now whenever I search for ad it finds & returns Adam, which is something that I don't want.

How would I search for case insensitive queries the right way? Thank you!

Here's my code for finding queries without case sensitivity, but with the regex bug.

server.get('/test/:username', (req, res)=> {
    const username = req.params.username

    usersDB.findOne({'username': {'$regex': username, $options: '?-i'}}, (err, data)=> {
        if(err) {
            throw err
        } 

        if(!data) {
            console.log('user not found')
            res.redirect('/')
        } else if(data) {
            console.log('user found: ' + data.username)
            res.redirect('/')
        }
    })
})
Gabriel Gavrilov
  • 337
  • 3
  • 11
  • 1
    Does this answer your question? [Case insensitive search in Mongo](https://stackoverflow.com/questions/8246019/case-insensitive-search-in-mongo) – sidgate Aug 20 '21 at 15:34
  • Hey @sidgate! I really appreciate you sending that, unfortunatly, no. I tried all of those responses and instead of fixing the search bug, it just returns a null. – Gabriel Gavrilov Aug 20 '21 at 18:14
  • 1
    you need to use the right regex `'^string$'` , to mark start and end of the string. alternatively use `$toLower` and match the lowercase string. – sidgate Aug 20 '21 at 18:18
  • Sorry man, I don't really understand what you're trying to say. Are you telling me to make it ``usersDB.findOne({'username': {'$regex': '^string$', $options: 'i'}}`` or ``usersDB.findOne({'username': {'$regex': '^username$', $options: 'i'}}`` because neither works. Thank you so much for helping me! – Gabriel Gavrilov Aug 20 '21 at 19:41

1 Answers1

1

You should set $options property to i value, and not ?-i:

{'username': {'$regex': `^${username}$`, $options: 'i'}}

Here is the working example: https://mongoplayground.net/p/wq0hfAnodmL

NeNaD
  • 18,172
  • 8
  • 47
  • 89