Karlis Filipsons
Karlis Filipsons

Reputation: 135

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()

Upvotes: 0

Views: 1428

Answers (1)

abdulbari
abdulbari

Reputation: 6242

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);
  });
}

Upvotes: 1

Related Questions