我有一个MongoDB数据库,其中包含城市,州和邮政编码列表。我希望能够运行一个查询,根据用户输入检查每个字段,并且无法确定如何执行此操作。以下是db中的文档示例:
{"_id":"92199","city":"San Diego","state":"CA"}
以下是我用来返回该文件的路线:
app.get('/city/:city', function(req, res){
var query = City.aggregate( [
{ $group: { _id: "$zip", city: {"$first" : "$city"}, state: {"$first" : "$state"} } },
{ $match: {"city": new RegExp(req.params.city, "i")} }
]);
query.exec(function(err, city){
if(err){
console.log(err);
return res.send(err);
}
console.log(city);
res.json(city);
});
});
问题在于,如果我查询San Diego,CA,查询将失败,因为它只搜索城市。如何查询city,state和zip(_id)以便仍然返回一个值?
答案 0 :(得分:0)
如果有人有兴趣,我最终会为我工作。可能会重构,但这有效:
app.get('/city/:city', function(req, res){
var location = req.params.city.replace(",", "");
location = toTitleCase(location);
location = location.split(" ");
for (var i = 0; i < location.length; i++) {
if(location[i].length == 2){
var state = location[i].toUpperCase();
var stateIndex = i;
}
if(!isNaN(parseFloat(location[i])) && isFinite(location[i])){
var zip = location[i];
var zipIndex = i;
}
}
if(zipIndex){
location.splice(zipIndex, 1);
}
if(stateIndex){
location.splice(stateIndex, 1);
}
location = location.join(" ");
if(state && zip){
var query = City.find({
$and: [
{ $and: [{"state": state}, {"city": new RegExp(location, "i")}] },
{ "zip" : zip }
]
});
}else if(zip){
var query = City.find({
$or : [{"city": new RegExp(location, "i")}, {"zip" : zip}]
});
}else if(state){
var query = City.find({
$and: [{"state": state}, {"city": new RegExp(location, "i")}]
});
}
else{
var query = City.find({
"city": new RegExp(location, "i")
});
}
query.exec(function(err, city){
if(err){
console.log(err);
return res.send(err);
}
res.json(city);
});
});
感谢@Semicolon对评论的帮助。