node.js - mongoDb:按距离选择所有用户

标签 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);
                    }
                });
        }

请帮帮我,我很绝望......

谢谢!

伊兰。

最佳答案

好的,我找到了。

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

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/

无论如何,谢谢。

关于node.js - mongoDb:按距离选择所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39227123/

相关文章:

MongoDB “empty” 或 NULL 日期

javascript - 为什么我在应用程序中使用 mongoose 时无法检索任何结果

scala - 从 scala 将文档插入 mongodb 时出错

javascript - Node 纤维中的运行与产量之间有什么区别

html - 在 Node 中渲染 HTML 字符串?

node.js - 从 Node.js 上的 Web Audio API 播放 PCM 流

mongodb - mongodb中实现带总页数的嵌入式分页

javascript - 从 mongoose 文档中获取纯 javascript 对象(或 JSON-ready 对象)

typescript - NestJS- Mongoose : cannot access fullDocument on ChangeEvent<any>

node.js - Node.js API 文档中的 {Object} 和 Object