javascriptnode.jsregexdatabasenedb

how do i pass a variable into search query of Nedb


i want to run a search function from the search bar of the website homepage that will query the **nedb ** database with the result gotten from **searchtext ** variable.

How do i pass the searchtext variable into the // as a regular expression? to find a title containing the content of searchtext variable.

Thanks for your help.

app.get("/search", (req, res) => {
  const searchtext = req.query.search;


  storydb.find({ title: // }, function (err, output) {
    if (err) {
      console.log(err);
    } else {
      console.log(output);
    }
  });

  res.render("search");
});

i have checked the documentation for the nedb on npm but don't seem to know how to pass the variable.

// Finding all planets whose name contain the substring 'ar' using a regular expression

db.find({ planet: /ar/ }, function (err, docs) { 

 // docs contains Mars and Earth});

Solution

  • Alright, after much research and iteration, I solved the problem. I wrapped the searchtext variable inside the RegExp function and stored that as another variable called regexObj. Then passed that new variable into the storydb.find() function.

    app.get("/search", (req, res) => {
      const searchtext = req.query.search;
      var regexObj = new RegExp(searchtext);
    
      storydb.find({ title: regexObj }, function (err, storycontent) {
        if (err) {
          console.log(err);
        } else {
          res.render("search", { storycontent });
        }
      });
    });