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! While you're at it, check out some resources Treehouse students have shared here.
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 trialJesse Thompson
10,684 PointsDifficulty 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
Front End Web Development Techdegree Graduate 84,738 PointsNot 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);
Jesse Thompson
10,684 PointsJesse Thompson
10,684 Pointsworked perfectly. Thankyou for clearing up this syntax problem very quickly for me.
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsNo problem.