Joh*_*ohn 5 html javascript ajax mongodb node.js
问题是,我的控制台出现错误:
{ [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 }
Run Code Online (Sandbox Code Playgroud)
基本上,我使用 Ajax 从我的 MongoDB 中获取数据,我在其中搜索用户。没有 Ajax,我的搜索功能可以正常工作,但我想搜索用户而不需要刷新网页,只需填写我的 HTML。这是我的所有代码:
服务器代码:
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});
}
});
});
Run Code Online (Sandbox Code Playgroud)
HTML代码:
<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>
Run Code Online (Sandbox Code Playgroud)
查询代码:
$("#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('');
}
});
});
Run Code Online (Sandbox Code Playgroud)
小智 2
// 名称 =${thename}
LoginUser.find({ $或: [
{"firstname": {$regex: `${thename}`, $options: 'i'}},
{"lastname": {$regex: `${thename}`, $options: 'i'}}
]
Run Code Online (Sandbox Code Playgroud)
},
| 归档时间: |
|
| 查看次数: |
4054 次 |
| 最近记录: |