0

I'm not able to run the geoNear query on my Mongo collection through mongoose. My schema looks like this: [1]: https://i.stack.imgur.com/rc0n5.jpg "schema". This is a screenshot of my indexes : [2]: https://i.stack.imgur.com/8qbGR.jpg "indexes".

 var url = 'mongodb://*******';

  MongoClient.connect(url, function(err, db) {
    if(err) {
      res.sendStatus(500)
    } else {
      if(db.places) {
        console.log("Connected successfully to server");
        var response = db.places.find({ coordinates : { $near : { $geometry : {
                  type : "Point" ,
                  coordinates : [req.query.lomg, req.query.lat] },
                  $maxDistance : 10000 /* 10 kms */
            }
          }
        })
        res.send(response)        
      }
      res.sendStatus(500);
    }
  });

The code is erroring out and always going to the else block thereby returning 500.

ShivaV
  • 21
  • 2
  • First of all you return 500 response in both `if` and `else` branches, basically always. Secondly `var response` is a promise. You need either to provide a callback to handle results of the queries or wait for the promise to be resolved or rejected. – Alex Blex Jun 10 '19 at 12:20

1 Answers1

0

Mongoose has some nice convenience functions to run geo queries on a collection.
An example from the docs:

const denver = { type: 'Point', coordinates: [-104.9903, 39.7392] };
return City.create({ name: 'Denver', location: denver }).
  then(() => City.findOne().where('location').within(colorado)).
  then(doc => assert.equal(doc.name, 'Denver'));

So in your case it would become something like:

db.find().where('coordinates').within({
                  type : "Point" ,
                  coordinates : [req.query.lomg, req.query.lat]});

If you want to use the MongoDb syntax directly, you can use the $aggregate operator, like so:

var response =
        db.aggregate([{
          $geoNear: {
            includeLocs: "coordinates",
            distanceField: 'distance',
            near: {type: 'Point', coordinates: [[req.query.lomg, req.query.lat]},
            maxDistance: 10000,
            spherical: true
          }
}]);

Note that the includeLocs field accepts a GeoJson geometry or plain coordinates. Check this blog post.

philoez98
  • 493
  • 4
  • 13