我正在使用MongoDB,Express,JS和Node创建类似Yelp的应用程序。通过搜索,我能够找到如何搜索校园模式的多个字段(校园,饭店,理发店,名称)。我现在想按位置(即洛杉矶的餐馆/企业)优化搜索,在此过程中需要帮助。这是我到目前为止尝试过的:
我尝试过Mongo的$ and / $ or命令。当我只使用$ or时,我可以按名称或位置进行搜索。
路线
router.get("/campus", function(req, res){
var noMatch = null;
if(req.query.search){
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
Campus.find({$and:[
{$or: [{name: regex}, {location:regex}, {food: regex},
{cost: regex}, {category:regex}]} ,
{$or: [{location: regex}]},
]},
function(err, allCampuses){
if(err){
console.log(err);
} else {
if(allCampuses.length < 1){
req.flash("error", "No campus match that search, please try
again.");
return res.redirect("back");
// noMatch = "No campus match that query, please try again.";
}
res.render("campus/index", {campus:allCampuses, currentUser:
req.user, noMatch: noMatch});
}
})
} else{
//get all campus from DB
Campus.find({}, function(err, allCampuses){
if(err){
console.log(err);
} else {
res.render("campuses/index", {campus:allCampuses, currentUser:
req.user, noMatch: noMatch});
}
})
}
})
HTML
<div class="container">
<header id="coverImage" class="jumbotron img-fluid">
<div class="container">
<h1>Welcome to CampusFinder</h1>
<p>View our hand-picked Campuses</p>
<p>
<a class="btn btn-primary btn-lrg" href="/bizs/new">Add New Campus</a>
</p>
<p>
<form action="/campuses" method="GET" class="form-inline">
<div class="form-group" >
<input type="text" name="search" placeholder="campuses
search" class="form-control">
<input type="submit" value="Search" class="btn btn default">
</div>
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location" id="location" placeholder="Florida">
</div>
</form>
</p>
</div>
</header>
我希望输出像Yelp一样工作。当我选择位置并搜索校园时,该城市的校园将会出现。
答案 0 :(得分:0)
我认为您应该从第一个条件中排除{location:regex}
,并使用另一个参数来捕获输入位置并赋予AND的第二个子句。
{
$and: [
{
$or: [
{ name: regex },
{ food: regex },
{ cost: regex },
{ category: regex }
]
},
{ location: locationRegex }
]
}