Reputation: 1068
I am trying to get results of nearby location from a specific point. By using a normal way of finding by ID, there is a result returned but when I am trying to find nearby location using the coordinates, no result is appearing. There wasn't any errors/warnings in my code but there wasn't any results too. What am I missing?
Model Schema
var locationSchema = new Schema({
fb_location: String,
coordinates:[]
});
var feed_postSchema = new Schema({
content: String,
location: [locationSchema],
image: [{ type : String }],
created_at: { type : Date, default: Date.now }
});
locationSchema.index({coordinates:'2dsphere'});
Server.js
app.get('/test_radar',function(request,response){
Feed_Post.find(
{
'location.coordinates' :
{
$near :
{
coordinates: [100,5]
},
$maxDistance: 100
}
},function(err,ret){
console.log(response.json(ret));
})
});
Sample Database Data
"_id" : ObjectId("5620a3c2fde01a55065f4c3b"),
"content" : "Test post",
"created_at" : ISODate("2015-10-16T07:14:10.636Z"),
"image" : [ ],
"location" : [
{
"fb_location" : "Malaysia",
"_id" : ObjectId("5620a3c2fde01a55065f4c3c"),
"coordinates" : [
100,
5
]
}
],
"__v" : 0
Note: I did set the $maxDistance to 100 * 1000. There is still no result.
Upvotes: 1
Views: 865
Reputation: 606
$near
operator requires a geospatial index.
If you want to define your location as a point using legacy coordinates you must have 2D index created. Then you will be able to use $near
operator in syntax you specified.
You created 2dsphere index so you must specify GeoJSON point in your query:
Feed_Post.find(
{
'location.coordinates' :
{
$geometry: {
type: "Point" ,
coordinates: [ 100 , 5 ]
},
$maxDistance: 100
}
},function(err,ret){
console.log(response.json(ret));
})
Check $near definition.
Upvotes: 1