Karlis Filipsons Karlis Filipsons - 2 months ago 10
Node.js Question

[SOLVED]Mongoose regex search with two conditions

I have to write a query that works as an autocomplete for finding a location. The else statement works fine on finding the right country but when a user writes "Germany,Berlin" for example the algorithm throws up other countries that might have a city called "Berlin". I need it to search only cities that are located in, for example, "Germany".

Just to make it clear the flag variable goes true when there is a comma in the search paramater string. It then splits up in country and city.

if(flag){
World.findOne().or([{name:{$regex:country}},{cities: {$regex:city}}]).exec(function (err, users) {
if (err) return console.error(err);
console.log(users);
res.send(users);
});
}else{
World.findOne({name:{$regex:val}}, {cities: {$slice: 10}}).exec(function (err, users) {
if (err) return console.error(err);
console.log(users);
res.send(users);
});
}


I tried this as well but it throws a compile error:

if(flag){
World.findOne({{country:{$regex:country}},{cities: {$regex:city}}}).exec(function (err, users) {
if (err) return console.error(err);
console.log(users);
res.send(users);
});


Tried the same with removing the outer brackets in findOne()

Answer

I think you are not giving proper query value.

Try this

if (flag) {
  World.find({
    country: {
      $regex: country
    },
    cities: {
      $regex: city
    }
  }).exec(function(err, users) {
    if (err) return console.error(err);
    console.log(users);
    res.send(users);
  });
}