Find issue in Express + MongoDB

I’ve been extending the Express + MongoDB “Local Library” sample application. I copied and modified book_list to create a page that shows the list of books with a search form. The search form is just a text box and a submit button.

// Books home POST (search results)
exports.books_home_post = function (req, res, next) {
  var moduleName = 'Books' + req.body.search_term;
  Book.find({ title: /^req.body.search_term/}, 'title author')
    .sort({ title: 1 })
    .populate('author')
    .exec(function (err, bookList) {
      if (err) {return next(err); }
      res.render('books_home', { title: moduleName, book_list: bookList });
    });
};

book_list is empty on return, but the assignment and later display of var moduleName shows that req.body.search_term does contain the search term.

Also, if I use Book.find({ title: /^some_unquoted_string/}, ‘title author’) it does work and book_list returns only the books with the unquote string in the title. Somehow, I need to indicate that req.body.search_term is not a literal string but the name of a property. Not sure how to do that, though.

Hi @RobertSF

When we want to build dynamic regular expressions we need to use the RegExp() constructor. From RegExp | MDN:

The constructor of the regular expression object—for example, new RegExp('ab+c') —results in runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and obtain it from another source, such as user input.

We create our desired regex string inside the RegExp() constructor and it turns it into a real regular expression. I think the following code should work:

const regex = new RegExp(`^${req.body.search_term}`);
Book.find({ title: regex}, 'title author')

Happy coding,
Michael

2 Likes