Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

Node.js and Mongoose return 2D query

I have a simple problem, I am trying to return a MongoDB document after a query in my Node.js server :

var coords = [];
        coords[0] = req.query.valArray.lng; // client latitude
        coords[1] = req.query.valArray.lat; // client longitude
        var distanceInKM = req.query.valArray.rangeKM; // the range 
         //the query that its results i want to return by res.send()
        db.Jobs.find( { 
            $and: [ { {exp: req.query.valArray.exp} }, 
                      { field: req.query.valArray.field } 
                  ] } )

My questions are:

  1. How to return the document according to the req.query (exp = query.exp ) and the rest of the params by the res.send() function.
  2. How to search by the coordination(coords) and the range from the current location (lng , lat), in other words create a radius from the coords that all matching jobs will return as a json.

Upvotes: 0

Views: 92

Answers (1)

Pio
Pio

Reputation: 4064

You don't need to reinvent the wheel. Your approach will not account for the curvature of the Earth so your calculations will be inaccurate if the distances are large.

I would advise to use Geospatial Indexes already supported by MongoDB.

UPDATE

For example you can use $centerSphere operator which returns documents within a radius from a central point (example taken from there).

{
  <location field>: {
     $geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] }
     }
}

To do this you need to store your coordinates in GeoJSON format (you need to add just a few meta fields to your html5 coordinates).

Upvotes: 1

Related Questions