Yerk
Yerk

Reputation: 1008

Why doesn't this Mongoose query work?

var latitude = 34
var longitude = -84

MyModel.find({
    "$and": [
       { "expiry" : { "$gt" : Date.now() } }
      ,{ "area.min-lat"   : { "$lte"  : latitude  } }
      ,{ "area.max-lat"   : { "$gte"  : latitude  } }
      ,{ "area.min-long"  : { "$lte"  : longitude } }
      ,{ "area.max-long"  : { "$gte"  : longitude } }
    ]
  }, 
  function(err, matches){
    if (!err) {
      callback(matches, null)
    } else { // there was an error
      console.log(err);
      callback(null, err);
    }
  });

executes without fail, but continues to return nothing. I've tried isolating the expiry and the map area parts, and neither works. Yet if I just do a find() or change the comparisons to a $ne, I get my result back. There is only one object in the database I'm trying to pull for testing...

"_id" : "543ee4e4e55422ab155f0a44",
    "name" : "Test Location Space",
    "img-url" : "http://s3.amazonaws.com/test/test/32098mfsnsdj09w.jpg",
    "expiry" : "2016-01-17T08:42:12.586Z",
    "area" : {
        "min-lat" : 33,
        "max-lat" : 35,
        "min-long" : -85,
        "max-long" : -83
    }

Upvotes: 0

Views: 456

Answers (2)

Yerk
Yerk

Reputation: 1008

So the problems here were my fault, and the code is mostly correct.

First, the latitude and longitude were actually strings (as parsed by Express's default middleware). For whatever odd reason though, only the max-lat subquery was thrown off by the string type. Commenting that out would cause the query to return the expected result. My solution to that was just ensuring the parameters were indeed a float.

Next, the date for my expiry was just a string, when really it should have been a date type. I created a new object through Mongoose, feeding it a native Javascript date type, which was stored as ISODate("2014-10-26T17:57:47.727Z"). My query for { "expiry" : { "$gt" : Date.now() } } now works as expected.

Upvotes: 1

Disposer
Disposer

Reputation: 6371

You should change

"expiry" : { "$gt" : Date.now() } 

to

{ 'expiry' : { $gt : Date.now().toString() }}

You are missing {} around that and convert date.now to string. it works for me

Upvotes: 1

Related Questions