0

I am making a dictionary web app and now I am trying to make a search engine. I want to partly enter a word and get all of the similar matches. For example, I enter "ava", and get "lava" and "available" back. Mongoose has a method to do that but I need to enclose my query into slashes (like this /query/). I can do that with a string but I don't know how to put a variable in there in order to make a user search.

// executes, name LIKE john and only selecting the "name" and "friends" fields

await MyModel.find({ name: /john/i }, 'name friends').exec();

Here's my code:

app.post("/search", function(req, res){
  let search = req.body.wordSearch;
  console.log(req.body.wordSearch);
  Dicword.find({word: /search/i}, function(err, searchRes) {
    search = searchRes;
    res.render("search", {search: search});
  } );
})

I use let search to store the query and a result of a search but when I put it in find method with slashes /search/, it gets recognized as a string and not a variable. How can I use a variable there?

magrega
  • 37
  • 7
  • Have you seen: [How I can use "LIKE" operator on mongoose?](https://stackoverflow.com/q/43729199)? – Nick Parsons Dec 17 '21 at 13:24
  • 1
    Does this answer your question? [How I can use "LIKE" operator on mongoose?](https://stackoverflow.com/questions/43729199/how-i-can-use-like-operator-on-mongoose) – Xeelley Dec 17 '21 at 13:26

1 Answers1

-1

Instead of

{ word: /search/i }

Write like this

{ word: `/${search}/i` }