`I have a list of listings in mongodb, so that each listing contains the following fields:
{
"city" : "Yucca Valley",
"county" : "San Bernardino",
"fullStreetAddress" : "7496 CHULA VISTA Avenue",
"state" : "CA",
"zipCode" : "92284",
"streetName" : "7496",
"streetNumber" : "CHULA VISTA",
"mls" : "41462506"
}
I have one search input and I'm trying to write a statement that searches by this columns and returns results. The query split searchQuery by space and search by each word.
For Yucca it returns correct result, but it works incorrect for Yucca Valley or Yucca Valley CA.
Here is my search query:
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 + "%"}}
]});
I guess, this happens because the last where overwrites the previous ones. Can anyone suggest how to modify this query that it'll return correct result.
I solved the problem by using .native() instead of .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")
}
})
})