Reputation: 11
Hoping someone can help with this because I've been working on it all morning
I'm trying to use MongoDB Near to find locations within a radius of a given point on a map. I get the following error:
{"name":"MongoError","message":"Can't canonicalize query :: caused by :: invalid argument in geo near query: spherical","$err":"Can't canonicalize query :: caused by :: invalid argument in geo near query: spherical","code":2,"ok":0}
This is the mongoose schema for locations:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var LocationSchema = new Schema({
title: String,
coordinates: {
type: [Number],
index: '2dsphere'
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('Location', LocationSchema);
and this is the route where I try to use "Near" - basically I enter a set of coordinates in a form where the target is the following
router.post('/nearme', function (req, res, next) {
// Setup limit
var limit = req.body.limit || 10;
// Default max distance to 10 kilometers
var maxDistance = req.body.distance || 10;
// Setup coords Object = [ <longitude> , <latitude> ]
var coords = [];
// Create the array
coords[0] = req.body.longitude;
coords[1] = req.body.latitude;
// find a location
Location.find({
'coordinates': {
$near: {
$geometry: {
type: "Point",
coordinates: coords
},
// distance to radians
$maxDistance: maxDistance * 1609.34, spherical: true
}
}
}).limit(limit).exec(function (err, stores) {
if (err) {
return res.status(500).json(err);
}
//res.status(200).json(stores);
res.render('locations', {
title: 'Locations',
location: stores,
lat: -23.54312,
long: -46.642748
});
});
Also - I indexed the location collection as follows:
db.locations.ensureIndex({ 'coordinates' : '2dsphere'})
and as far as I can tell, it looks right:
Things I've tried:
spherical:true
Any help you could provide would be amazing. Thank you!
Upvotes: 0
Views: 661
Reputation: 11
Thanks to Joe I reviewed the MongoDB docs and updated the /nearme route as follows (changes made in $near):
router.post('/nearme', function (req, res, next) {
// Setup limit
var limit = req.body.limit || 10;
// Default max distance to 10 kilometers
var maxDistance = req.body.distance || 10;
// Setup coords Object = [ <longitude> , <latitude> ]
var coords = [];
// Create the array
coords[0] = req.body.longitude;
coords[1] = req.body.latitude;
// find a location
Location.find({
'coordinates': {
$near: {
$geometry: {
type: "Point" ,
coordinates: coords
},
$maxDistance: maxDistance * 1609.34,
$minDistance: 0
}
}
}).limit(limit).exec(function (err, stores) {
if (err) {
return res.status(500).json(err);
}
//res.status(200).json(stores);
res.render('locations', {
title: 'Locations',
location: stores,
lat: -23.54312,
long: -46.642748
});
});
});
Upvotes: 0