0

I am querying Mongoose db with a search, where the title is the "customTitle" from the URL.

The search works well if I search for all items, e.g. Article.find(err, foundArticles) =>, but I am getting an empty query response to Article.find({title:/customTitle/i}, (err, foundArticles) => {

I'd like to get a response with all items, that contains "customTitle" variable in any record.

app.route("/:customTitle")
.get(function(req, res){
  const customTitle = _.capitalize(req.params.customTitle);
  Article.find({title:/customTitle/i}, (err, foundArticles) => {
  if (!err){
    res.send(foundArticles);
    console.log(typeof customTitle +" ", customTitle);
    console.log(foundArticles);
  } else {
    res.send(err);
  }
});

What is the problem here, please? Thank you.

2 Answers 2

1

You need to create the regex using new RegExp. You are searching for the literal string customTitle.

For example:

const rx = new RegExp(customTitle, 'i')
query.find({title:rx})
Sign up to request clarification or add additional context in comments.

4 Comments

Could you please check what else is wrong there? I'm getting still empty response. Thank you
You might have characters that need escaping. Post your error.
Also, hardcode a simple string in the regex instead of using input from query, and see if it works.
Ok, both work now, so I edited the answer, and I leave it here for others. Thanks!
1

I've found, that I can use RegExp of Mongoose and JavaScript

Mongoose RegExp that works:

app.route("/:customTitle")
  .get(function(req, res) {
    const customTitle = _.capitalize(req.params.customTitle);
    Article.find({ title: {$regex: customTitle, $options:'i'}}, (err, foundArticles) => {
      if (!err) {
        res.send(foundArticles);
      } else {
        res.send(err);
      }
  });

And JavaScript RegExp that works:

  app.route("/:customTitle")
    .get(function(req, res) {
      const customTitle = _.capitalize(req.params.customTitle);
      const rx = new RegExp(customTitle, 'i');
      Article.find({title:rx}, (err, foundArticles) => {
        if (!err) {
          res.send(foundArticles);
        } else {
          res.send(err);
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.