`我在mongodb中有一个列表清单,因此每个清单都包含以下字段:
{
"city" : "Yucca Valley",
"county" : "San Bernardino",
"fullStreetAddress" : "7496 CHULA VISTA Avenue",
"state" : "CA",
"zipCode" : "92284",
"streetName" : "7496",
"streetNumber" : "CHULA VISTA",
"mls" : "41462506"
}
我有一个搜索输入,我正在尝试编写一个语句,按此列搜索并返回结果。查询按空格分割searchQuery并按每个单词搜索。
对于Yucca
,它会返回正确的结果,但对Yucca Valley
或Yucca Valley CA
的效果不正确。
这是我的搜索查询:
var searchQuery = req.param('q') ? req.param('q').trim() : null;
if (searchQuery) {
var searchQueryArray = searchQuery.split(" ");
var page = req.param('page') ? req.param('page') : 1;
var pageData = {};
var query = Property.find()
searchQueryArray.forEach(
function (queryItem){
var orNumeric = [];
var orStrings = [];
console.log(queryItem);
// check, if word contains only numbers, compare it to numeric fields
if(/^\d+$/.test(queryItem)){
orNumeric.push({streetNumber: {like: "%" + queryItem + "%"}});
orNumeric.push({zipCode: {like: "%" + queryItem + "%"}});
orNumeric.push({mls: {like: "%" + queryItem + "%"}});
query.where({or: orNumeric});
} else {
orStrings.push({streetName: {like: "%" + queryItem + "%"}});
orStrings.push({city: {like: "%" + queryItem + "%"}});
orStrings.push({state: {like: "%" + queryItem + "%"}});
query.where({or: orStrings})
}
}
);
query.where({or: [
{"fullStreetAddress": {like: "%" + searchQuery + "%"}}
]});
我想,这是因为最后where
覆盖了之前的{{1}}。任何人都可以建议如何修改此查询,它将返回正确的结果。
答案 0 :(得分:0)
我使用.native()
代替.query()
解决了这个问题。
var searchQueryArray = searchQuery.split(" ");
var andQuery = [];
searchQueryArray.forEach(
function (queryItem) {
var orNumeric = [];
var orStrings = [];
// check, if word contains only numbers, compare it to numeric fields
if (/^\d+$/.test(queryItem)) {
orNumeric.push({"streetNumber": {'$regex': ".*" + queryItem + ".*"}});
orNumeric.push({"zipCode": {'$regex': ".*" + queryItem + ".*"}});
orNumeric.push({"mls": {'$regex': ".*" + queryItem + ".*"}});
andQuery.push({"$or": orNumeric})
} else {
orStrings.push({"streetName": {'$regex': ".*" + queryItem + ".*"}});
orStrings.push({"city": {'$regex': ".*" + queryItem + ".*"}});
orStrings.push({"state": {'$regex': ".*" + queryItem + ".*"}});
orStrings.push({"fullStreetAddress": {'$regex': ".*" + queryItem + ".*"}});
andQuery.push({"$or": orStrings})
}
}
);
Listing.native(function (err, collection) {
if (err) return res.serverError(err);
collection.find({"$and": andQuery})
.sort({"createdAt": -1})
.toArray(function (err, matchedListings) {
if (err){
return res.serverError(err);
}
else {
console.log("Continue code")
}
})
})