mongoDb:按距离

时间:2016-08-30 12:09:41

标签: node.js mongodb mongoose mongodb-query

我试图让我的所有用户根据他们与mongoDb的距离,我刚看到我可以使用“nearSphere”来做到这一点:

{
  $nearSphere: {
     $geometry: {
        type : "Point",
        coordinates : [ <longitude>, <latitude> ]
     },
     $minDistance: <distance in meters>,
     $maxDistance: <distance in meters>
  }
}

这是我的功能:

function getUsersByDistance(req, res, next) {
var range = req.params.distance; //(For example: 3000)
          console.log("Searching for users that far away from me in: " + req.params.distance + "Km");

    //First, lets find my latitude and longitude
    User.findOne({_id: req.params.userId}).populate("user").exec(function (err, user) {
                if (err) {
                    res.jsonp({error: "Error fetching user info"})
                } else {
                    if (!user) {
                        res.jsonp({error: "User not found"});
                    } else {
    //Found it!
        //user.latitude = x
        //user.longitude = y

    //Now I need to fins all users within the range (HERE I NEED YOUR HELP):
    var query = //"{ distance is maximum Z distance from my position }"

    //Then, search all users inside this range:
            Users
                .find(query)
                .sort('-created')
                .exec(function (err, questions) {
                    if (err) {
                        return res.send({
                            errors: err
                        });
                    } else {
                        //Here I should have all users with maximum distance Z from my position
        res.jsonp(users: users);
                    }
                });
        }

请帮助我,我绝望......

谢谢!

叶兰。

1 个答案:

答案 0 :(得分:1)

好的,我找到了。

首先,您必须以这种方式保存在您的用户(或您的架构中的任何其他位置)的位置:

loc: {
    type: [Number],  // [<longitude>, <latitude>]
    index: '2d'      // create the geospatial index
    }

然后,您将能够使用:

进行搜索
findLocation: function(req, res, next) {  
    var limit = req.query.limit || 10;

    // get the max distance or set it to 8 kilometers
    var maxDistance = req.query.distance || 8;

    // we need to convert the distance to radians
    // the raduis of Earth is approximately 6371 kilometers
    maxDistance /= 6371;

    // get coordinates [ <longitude> , <latitude> ]
    var coords = [];
    coords[0] = req.query.longitude;
    coords[1] = req.query.latitude;

    // find a location
    Location.find({
      loc: {
        $near: coords,
        $maxDistance: maxDistance
      }
    }).limit(limit).exec(function(err, locations) {
      if (err) {
        return res.json(500, err);
      }

      res.json(200, locations);
    });
}

我在这里找到了它: http://blog.robertonodi.me/how-to-use-geospatial-indexing-in-mongodb-using-express-and-mongoose/

非常感谢。