Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Jesse Thompson
Jesse Thompson
10,684 Points

Difficulty making wildcard search in mongodb using react/express

I am having an issue with syntax for my wildcard username search for an app I am building.

So I have a fetch request on the client side. It sends the body and in body I have a variable under searchusers which is the string put into the search input.

Now for some reason if I type User.find({username: /a/ } it will return every user with a username containing a. But if the variable is equal to usersearch = '/' + 'a' + '/' and I instead type what is below it does not work.

What is the correct way to write a mongodb wildcard query using a variable?

 router.post('/searchusers', (req, res, next) => {
    let usersearch = '/' + req.body.searchusers + '/';
    User.find({username: usersearch}, function(err, result) {
        if (err) throw err;


1 Answer

Brendan Whiting
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,733 Points

Not 100% sure, but I think the issue is that regular expressions in JavaScript aren't wrapped in quotes, they're wrapped in just slashes. So I think what you want to do is use the RegExp constructor and pass in the string variable.

let usersearch = new RegExp(req.body.searchusers);