Find a string in mongodb with a regex expression and using a variable

Viewed 29

Trying to use mongodb .find with node and I can't figure out how to replace the regex expression with a variable.

So the user is doing a search for text in a blogpost. I'm then using that text to query mongo for any posts that have that text in the title. So if they were searching for posts with a 'Dragon' in them I'm trying to recreate the below using the input, and need it to be not be case sensative.

BlogPost.find({ title:/Dragon/},
app.post('/', async(reg, res) => {
    const searchTerm = `/${reg.body.search}/i`;
    console.log(searchTerm);
    const blogposts = await BlogPost.find({ title: searchTerm });

    res.render('index', { blogposts });
});```


1 Answers

Figured it out for anyone who comes across this in the future. By creating an new instance of RegExp with the variable passed to it. The ā€˜i’ being to make it case-insensitive.

app.post('/', async(reg, res) => {
  const searchTerm = reg.body.search;
  const blogposts = await BlogPost.find({ title: new RegExp(searchTerm, 'i') });
  res.render('index', { blogposts });
});
Related