gpt4 book ai didi

javascript - MongoError $regex 必须是一个字符串

转载 作者:行者123 更新时间:2023-12-03 12:13:17 28 4
gpt4 key购买 nike

问题是,我的控制台出现错误:

{ [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 }
基本上,我使用 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});
}
});
});
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>
jQuery代码:
$("#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}登录用户.find({
$或:[

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

关于javascript - MongoError $regex 必须是一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39823659/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com