Note: $near returns empty array instead of nearest locations in mongoose
Basically, I am trying to return the nearest locations from the given location in nodejs.
I’ve tried to implement several answers from S.O. but they didn’t work.
I’m able to post data in this schema and also able to fetch it. But when I pass some long, lat in Get request of postman URL, it returns me an empty array instead of actual data.
Here is my schema looks like
Model.js
const ShopSchema = new Schema({
shop_name: {
type: String,
required: true
},
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
default: [0,0],
}
}
});
ShopSchema.index({location: "2dsphere"});
const Shops = mongoose.model('Shops', ShopSchema);
module.exports = Shops;
Controller.js
exports.getNearestShops = async (req, res) => {
// trimming to get only values after = sign and parse it to float
const long = parseFloat(req.params.long.split("=").pop());
const lat = parseFloat(req.params.lat.split("=").pop());
try {
// Shops is model imported from model.js
const resData = await Shops.find({
location: {
$near: {
$maxDistance: 5000,
$geometry: {
type: "Point",
coordinates: [long, lat]
},
},
},
});
console.log(resData);
return res.send(resData)
} catch (err) {
console.log(err);
return res.send(err);
}
}
On passing the longitude and latitude in the postman URL, it returns me []. Even though I have stored coordinates that fulfill the $maxDistance: 5000