简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM