node.js - Mongodb $geoNear operator not working correctly -
i'm building nodejs api using mongodb database android app. when android user sends gps position end, api sorts data distance user , replies back.
for this, i'm using $geonear stage in aggregation framework. followed instructions, can't data, "undefined".
here json data format db.
{ userid: "", description: "", location: { type: "point", coordinates: [ latitude, longitude ] }, image: "" }
and here geonear code.
db.posts.createindex({location:"2dsphere"}); db.posts.aggregate([ { $geonear: { near: { type: "point", coordinates: [ parsefloat(geoinfo.latitude) , parsefloat(geoinfo.longitude) ] }, distancefield: "distance", spherical: true } }, { $sort: { distance: 1 } }, { $limit: 20 } ], function(err, docs) { if (err) { callback(err, null); } callback(null, docs); });
i can see undefined result. i'm stuck in issue few days. helps appreciated!
here working code.
db.open(function(err, db) { var collection = db.collection("posts"); console.log(collection.listindexes); // wait second before finishing up, ensure have written item disk settimeout(function() { collection.aggregate([ { $geonear : { near : { type : "point", coordinates : [ parsefloat(-73.97), parsefloat(40.77) ] }, distancefield : "distance", spherical : true } }, { $sort : { distance : 1 } }, { $limit : 20 } ], function(err, docs) { if (err) { console.log(err); } console.log("completed..........."); console.log("doc ====>" + json.stringify(docs)); }); }, 1000); });
inserts , create index commands:-
db.posts.insert( { userid : "user1", description : "desc 1", loc : { type: "point", coordinates: [ -73.97, 40.77 ] }, name: "central park", category : "parks", image : "image 1" } ) db.posts.insert( { userid : "user2", description : "desc 2", loc : { type: "point", coordinates: [ -73.88, 40.78 ] }, name: "la guardia airport", category : "airport", image : "image 2" } ) db.posts.createindex( { loc : "2dsphere" } )