javascript - Node.js 和 Mongoose 返回 2D 查询

标签 javascript json node.js mongodb 2dsphere

我有一个简单的问题,我试图在 Node.js 服务器中查询后返回 MongoDB 文档:

var coords = [];
        coords[0] = req.query.valArray.lng; // client latitude
        coords[1] = req.query.valArray.lat; // client longitude
        var distanceInKM = req.query.valArray.rangeKM; // the range 
         //the query that its results i want to return by res.send()
        db.Jobs.find( { 
            $and: [ { {exp: req.query.valArray.exp} }, 
                      { field: req.query.valArray.field } 
                  ] } )

我的问题是:

  1. 如何根据 req.query (exp = query.exp ) 返回文档,并通过 res.send() 函数返回其余参数。
  2. 如何通过坐标(coords)和当前位置的范围(lng,lat)进行搜索,换句话说,从坐标创建一个半径,所有匹配的作业都将以 json 形式返回.

最佳答案

您不需要重新发明轮子。您的方法不会考虑地球的曲率,因此如果距离很大,您的计算将不准确。

我建议使用 Geospatial Indexes MongoDB 已支持。

更新

例如,您可以使用 $centerSphere运算符返回以中心点为中心的半径范围内的文档(示例取自那里)。

{
  <location field>: {
     $geoWithin: { $centerSphere: [ [ <x>, <y> ], <radius> ] }
     }
}

为此,您需要将坐标存储在 GeoJSON 中格式(您只需向 html5 坐标添加一些元字段)。

关于javascript - Node.js 和 Mongoose 返回 2D 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29365383/

相关文章:

javascript - React - 单独脚本中的组件不起作用

android - 使用 Retrofit 在 JSON 中上传多部分图像数据?

forms - nodejs 表单模块 : how to add class to a field

node.js - 如何在 Node Js 中使用 Mongodb Bulk 和多文档事务?

Node.js + Socket.io + Redis 应用程序通过 PM2,内存占用较大

javascript - 如何从解析数据库保存全局变量值

javascript - 如何使用模拟 api 调用测试 React 组件

javascript - 在指令模板中时,如何使 Angular ui-router ui-sref 工作?

PHP |从 URL 获取 JSON 数据并将其放入数组只显示一项?

java - 使用 json-simple 库在 Java 中解码 JSON 字符串