I have a Schema (Tour) which includes a GeoJSON Point type property called location.
location: {
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
},
index: '2dsphere'
},
The controller function for creating a tour is as follows:
const createTour = async (req, res) => {
var newTour = new TourDB.Tour({
...
location: { type: 'Point', coordinates: [req.body.tour.loc[0], req.body.tour.loc[1]] },
...
})
newTour.save(async (err, doc) => {
if (!err) {
return res.status(200).send(doc)
} else {
return res.status(500).send({ errorMessage: err })
}
})
In the frontend, a new Tour can be created with this property: loc: [this.lng, this.lat],
This is how it will look in MongoDB:
https://i.stack.imgur.com/m0qqD.png
To query the location within a radius, I attempted the following in my controller (radius and maxDistance values are hardcoded for testing):
const getTourByRadius = async (req, res) => {
let coords = [];
coords[0] = 9.825031;
coords[1] = 48.625107799999995
const maxDistance = 10;
try {
const tour = await TourDB.Tour.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: coords
},
$maxDistance: maxDistance
}
}
}).exec()
res.send(tour)
} catch (err) {
res.send(err)
}
}
However, I am currently receiving an empty [] array as a result. What could I be doing wrong?