How to execute runCommand with Mongoose?

前端 未结 4 485
一生所求
一生所求 2021-02-07 13:28

I am using Node.js and Mongoose to access my MongoDB. I am using a model that stores some geo coordinates. I have them indexed and everything seems to work as expected. What I a

4条回答
  •  鱼传尺愫
    2021-02-07 14:01

    First of all there is not yet a convenience wrapper to use geoNear with Mongoose directly (given that you want to read the calculated distance).

    But since Mongoose collections proxies all collection methods from the native MongoDB native driver you can just use their geoNear method, though you have to give up a little bit of convenience you might expect from Mongoose and in my findings the error handling was a little bit different.

    Anyway, this is how you could use said API:

    YourModel.collection.geoNear(lon, lat, {spherical: true, maxDistance: d}, function(err, docs) {
      if (docs.results.length == 1) {
        var distance = docs.results[0].dis;
        var match = docs.results[0].obj;
      }
    });
    

    Please refer to the docs for correct error handling and how to calculate the distances.

提交回复
热议问题