Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError $regex has to be a string

The problem is, I'm getting an error in my Console:

{ [MongoError: $regex has to be a string]
  name: 'MongoError',
  message: '$regex has to be a string',
  waitedMS: 0,
  ok: 0,
  errmsg: '$regex has to be a string',
  code: 2 }

Basically I'm using Ajax to get data from my MongoDB, where I'm searching for a user. Without Ajax, my search function is working correctly, but I want to search for a user without the need of refreshing the web-page and just fill up my HTML. Here is all my code:

Server code:

app.post("/searchresult", function(req, res){
    var thename = req.body.thename;
    LoginUser.find({
        $or: [

            {"firstname": {$regex: thename, $options: 'i'}},
            {"lastname": {$regex: thename, $options: 'i'}}
        ]
    }, function(err, searchedUser){
        if(err){
            console.log(err);
            res.redirect("back");
        } else {
            res.render("searchprofile", {foundUser: searchedUser});
        }
    });
});

HTML code:

<form class="form-inline" id="searchform" action="/searchresult" method="POST">
   <input type="text" class="form-control" placeholder="Search people" name="thename" id="searchinput">
   <button type="submit" class="btn btn-default">Submit</button>
</form>

JQuery code:

$("#searchform").on('submit', function(e){
  e.preventDefault();

  var searchInp = $("#searchinput");

  $.ajax({
    url: '/searchresult',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ firstname: searchInp.val() }),
    success: function(response){
      console.log(response);
      searchInp.val('');
    }
  });
});
like image 387
John Avatar asked Nov 08 '22 08:11

John


1 Answers

// thename = ${thename}

LoginUser.find({ $or: [

    {"firstname": {$regex: `${thename}`, $options: 'i'}},
    {"lastname": {$regex: `${thename}`, $options: 'i'}}
]

},

like image 84
lucotmo Avatar answered Nov 14 '22 23:11

lucotmo