Phumu Mahandana
Phumu Mahandana

Reputation: 95

Mongoose passing coordinates to find() method for geospartial search?

I have a list of locations with a field "location" that has coordinates. I am trying to use the $near operator to query all locations within a specified distance from the given coordinates.

I want users to pass their own coordinates on the frontend. This is my code

const lon = req.params.lon;
const lat = req.params.lat;
const shops = await Shop.find({
  location: {
    $near: {
      $maxDistance: 1000,
      $geometry: {
        type: "Point",
        coordinates: [lon, lat],
      },
    },
  },
});

return res.status(200).json({
  success: true,
  data: shops,
});

When I try passing the latitude and longitude through params on the URL, I get nothing, is there another way I can use to pass the coordinates to the request?

My URL was something like this: "localhost:5000/api/shops/lat/lon"

Where lat is the latitude, and on is the longitude coordinates.

Upvotes: 0

Views: 731

Answers (1)

Luis Orbaiceta
Luis Orbaiceta

Reputation: 473

NOTE: Don't forget to add ':' before the params in your url as mentioned: api/:lon/:lat

As you have correctly defined your query, your problem might lie in the schema definition. Try casting to a 2D Sphere, and double check you are getting the params correctly and the distance matches your document.

const schema = new Schema({Your schema})
// CAST TO 2D SPHERE
schema.index({location: "2dsphere"});

Upvotes: 1

Related Questions