简体   繁体   中英

How to run geospatial queries using mongoose?

I'm not able to run the geoNear query on my Mongo collection through mongoose. My schema looks like this: [1]: https://imgur.com/kIPAHRV "schema". This is a screenshot of my indexes : [2]: https://imgur.com/DvyHxK5 "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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM