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('');
}
});
});
// thename = ${thename}
LoginUser.find({ $or: [
{"firstname": {$regex: `${thename}`, $options: 'i'}},
{"lastname": {$regex: `${thename}`, $options: 'i'}}
]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With