Search code examples
node.jsregexmongodbexpresspug

Mongodb Nodejs Regex Search


Hey I am making a website which as a partial search form. Reference from:https://www.youtube.com/watch?v=ZC2aRON3fWw&t=42s But I couldnt understand why it doesnt work. I use pug instead of hbs.

And these are my codes:

    app.get('/sonuc', function(req, res, next){
  var q = req.query.q;
  Article.find({
    title : {
      $regex: new RegExp(q)
    }
  }, {
    _id:0,
    __v:0
    }, function(err, data){
      res.render('sonuc', {data:data})
    }).limit(10);
  });
});

Then this is my layout pug:

.ui-widget
      form.form-inline.my-2.my-lg-0
        input.form-control.mr-sm-2(type='text', onkeyup='showResults(this.value)', placeholder='Search',action='/article/'+sorgu, aria-label='Search')
        button.btn.btn-secondary.my-2.my-sm-0(type='submit')
        #search-results(style='width:60px;top:-1px;position:relative')

In this layout pug I thing the onkeyup issue is not working. How can I implement that fu nction on that form?

And ths is my main.js whihc takes query from database and write it in html form:

    var showResults = debounce(function(arg){
  var value = arg.trim();
  if(value == "" || value.length <= o){
    $("#search-results").fadOut();
    return;
  }else{
    $("#search-results").fadeIn();
  };
  var jqhr = $.get('/article/' + value, function(data){
  })
  .done(function(data){
    if(data.length == 0){
      $("search-resuts").append('<p classs="lead text-center mt-2">No Results</p>');
  }else{
    data.forEach(x => {
      $("search-resuts").append('<a href="#"><p class="m-2 lead"><img style="width:60px;" src="images/supreme1.jpg">' + x.title +'</p></a>');
    });
  }
  })
  .fail(function(err){
    console.log(err);
  })
}); 200;
function debounce(func, wait, immediate){
  var timeout;
  return function(){
    var context = this;
    args = arguments;
    var later = function(){
      timeout= null;
      if(!immediate)func.apply(context,args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if(callNow)func.apply(context,args);
    };
  };

I cannot understand these issues and why it doesnt work.As a summary, I want to make a search engine which works with regex and mongodb. İt will be partial that is shown in that youtoube video which is on the above of my article that I referenced. But the real issue is, I couldnt understand the code block of function showResults and I dont know how to translate this codes to my project. So that I am waiting your help. I cannot upload a video to this website so that if you can give me your facebook, instagram or email account I can send the issue which should be solved. I need your help. I have been making this project for a long time for my school but I cannot move on. Please I need your help. I hope I could express myself well and your helps will solve it.


Solution

  • Yes I got it know. I have made lots of changes instead of using this code blockes. I wathced : https://www.youtube.com/watch?v=9_lKMTXVk64 And also I documented : Fuzzy Searching with Mongodb? These two documentations help me a lot. So that my code is almost approximately 90% same as shown in these documentations. This is my app.js :

    app.get('/sonuc', function(req, res){
      if (req.query.search) {
        const regex = new RegExp(escapeRegex(req.query.search), 'gi');
        Article.find({ "title": regex }, function(err, articles) {
            if(err) {
                console.log(err);
            } else {
               res.render("index", { 
                 articles: articles 
                });
            }
        });
      }
    });
    

    This is my index.pug file :

    extends layout
    
    block content
      body
        br 
        br
        br
        ul.list-group
          each article, i in articles
            li.list-group-item
              a(href="/article/" + article._id)= article.title
    

    And this is my layout.pug file(But I will consider the text form)

      form.form-inline.my-2.my-lg-0(action="/sonuc" method="GET")
        input.form-control.mr-sm-2(type='text', name,="search", onkeyup='showResults(this.value)', placeholder='Search',action='/article/'+sorgu, aria-label='Search')
        button.btn.btn-secondary.my-2.my-sm-0(type='submit')
    

    Please look at: https://github.com/nax3t/fuzzy-search

    Because in my solution I didnt add the message that is applied when we cannot find the word. Or when there is no such a word which is searched by user. The noMatch query. But after I will apply it to my project I will add it to here.