Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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) => {
    console.log(req.body);
    let usersearch = '/' + req.body.searchusers + '/';
    console.log(usersearch);
    User.find({username: usersearch}, function(err, result) {
        if (err) throw err;
        console.log(result)

    });
});

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,696 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);