使用MEAN技术栈中的Mongoose,在给定坐标和最大距离的情况下查找最接近某个点的点 - 查询结果未定义。

14
I've有一个问题,几天来我都没能解决它,即使查看了相关的Stack Overflow Q/A。
我正在开发一个应用程序,重用Scotch's Create a MEAN Stack Google Map App Tutorial by Ahmed Haque的方法。
我正在尝试实现一个应用程序,使用Google Maps API绘制包含在MongoDB实例中的GeoJson文件中的坐标的Points、LineStrings和Polygons。
我使用Mongoose构建我的数据模式并查询我的MongoDB数据库。
我想找到最接近某个点P0的最近点CP,给定P0的纬度和经度以及给定的最大半径distance用于寻找感兴趣的点。

enter image description here

在给定的图像上,例如如果我插入2000(公里),我的查询将找到距离P0最多2000公里的所有点。在此示例中,它可能会给我P1和P2。
当我的Mongoose Schema中只有Points时,我能够做到这一点。
我只有标记(Points)的此Schema:
// Pulls Mongoose dependency for creating schemas
var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;

// Creates a User Schema. 
var MarkerSchema = new Schema({
    username: {type: String, required: true},
    location: {type: [Number], required: true}, // [Long, Lat]
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Indexes this schema in 2dsphere format
MarkerSchema.index({location: '2dsphere'});

module.exports = mongoose.model('mean-markers', MarkerSchema);

这是我的仅标记的旧查询

var User = require('./model.js');

app.post('/query/', function(req, res) {

        // Grab all of the query parameters from the body.
        var lat = req.body.latitude;
        var long = req.body.longitude;
        var distance = req.body.distance;
        var reqVerified = req.body.reqVerified;

        // Opens a generic Mongoose Query
        var query = User.find({});

        // ...include filter by Max Distance (converting miles to meters)
        if (distance) {

            // Using MongoDB's geospatial querying features
            query = query.where('location').near({
                center: {
                    type: 'Point',
                    coordinates: [long, lat]
                },

                // Converting meters to miles
                maxDistance: distance * 1609.34,
                spherical: true
            });
        }
});

它表现得非常好,我能够获得接近的分数。
然后,我更改了我的“模式”,使其更具动态性,并支持Polyline和Polygon。
我能够使用以下“模式”插入和绘制新的点、线和面:
var mongoose = require('mongoose');
var GeoJSON  = require('geojson');
var Schema   = mongoose.Schema;

// Creates a Location Schema.
var LocationSchema = new Schema({
                                    name: {type: String, required: true},
                                    location: {
                                      type: {type : String, required: true},
                                      coordinates : [Schema.Types.Mixed]
                                    },
                                    created_at: {type: Date, default: Date.now},
                                    updated_at: {type: Date, default: Date.now}
});

LocationSchema.index({location: '2dsphere'});
module.exports = mongoose.model('mean-locations', LocationSchema);

这是我的Mongoose查询

var GeoObjects = require('./model.js');

app.post('/query/', function(req, res) {

    // Grab all of the query parameters from the body.
    var lat = req.body.latitude;
    var long = req.body.longitude;
    var distance = req.body.distance;

    var query;

    if (distance) {
        query = GeoObjects.find({'location.type':'Point'})
                    .where('location.coordinates').near({
                      center: {
                        type: 'Point',
                        coordinates: [lat, long]
                      },
                      // Converting meters to miles
                      maxDistance: distance * 1609.34,
                      spherical: true
        });
    }

    // Execute Query and Return the Query Results
    query.exec(function(err, users) {
        if (err)
            res.send(err);
        console.log(users);
        // If no errors, respond with a JSON of all users that meet the criteria
        res.json(users);
    });
});

console.log(users);输出undefined。

在我的queryCtrl.js中记录查询结果会出现以下错误信息:

name: "MongoError", message: "error processing query: ns=MeanMapApp.mean-locatio…ed error: unable to find index for $geoNear query", waitedMS: 0, ok: 0, errmsg: "error processing query: ns=MeanMapApp.mean-locatio…ed error: unable to find index for $geoNear query"

稍有不同但意思相同:

app.post('/query/', function(req, res) {

    // Grab all of the query parameters from the body.
    var lat = req.body.latitude;
    var long = req.body.longitude;
    var distance = req.body.distance;

    console.log(lat,long,distance);

    var points = GeoObjects.find({'location.type':'Point'});

    var loc = parseFloat(points.location.coordinates);
    console.log(JSON.stringify(loc));

    if (distance) {
        var query = points.near(loc, {
                      center: {
                        type: 'Point',
                        coordinates: [parseFloat(lat), parseFloat(long)]
                      },
                      // Converting meters to miles
                      maxDistance: distance * 1609.34,
                      spherical: true
        });
    }
});

这是一个标记示例:

{
  "name": "user01",
  "location": {
                "type":"Point",
                "coordinates": [102.0, 0.0]

  }
}

$near操作符如何与距离和最大距离一起使用:

来自Ahmed Haque的Scotch's Making MEAN Apps with Google Maps(第二部分)

MongoDB搜索参数$near及其关联属性maxDistance和spherical用于指定我们要覆盖的范围。 我们将查询体的距离乘以1609.34,因为我们希望将用户输入(以英里为单位)转换为 MongoDB期望的单位(以米为单位)。

  1. 为什么会返回undefined
  2. 这个问题可能是由我的Schema引起的吗?
  3. 我该如何解决这个问题?

如果您需要一些澄清,请在下面发表评论。

提前致谢。


1
嗨 @AndreaM16,您有没有把这段代码放在GitHub或其他地方,以便我们可以下载下来仔细查看的机会呢? - Ahmed Haque
嗨,艾哈迈德,你看了吗? - AndreaM16
2个回答

5
我不知道你的代码下面是什么,但我知道一件事:
如果您使用Google雷达搜索,必须考虑以下内容:

最大允许半径为50,000米。

请查看他们的文档
这意味着,如果您尝试使用更大的半径,则可能会得到零结果。

1
嗨,非常感谢你的回答。我并没有使用谷歌的雷达搜索,而是尝试使用MongoDb的near和geoNear运算符。事实上,就像我之前写的那样,当我有一个不同的Mongoose模式(只有标记)时,我的查询正常工作。MongoDB搜索参数$near及其相关属性maxDistance和spherical用于指定我们希望覆盖的范围。我们将查询体的距离乘以1609.34,因为我们希望将用户输入的距离(以英里为单位)转换为MongoDB所期望的单位(以米为单位)。 - AndreaM16
1
关于你的代码行 console.log(users),我曾经遇到过类似的问题。问题在于JS的非阻塞特性,它比响应更快地执行了日志记录。在我的情况下,使用Promise或回调函数解决了这个问题。你尝试过这种方法吗? - Soldeplata Saketos
是的,我已经尝试过了,但它总是会得到未定义。我认为问题有点是由我的新模式和near操作符引起的。 - AndreaM16

1

我终于成功解决了这个问题。

本质上,这个问题是由模式引起的,因为2dIndex引用了一个错误的字段(type and coordinates)

我使用以下模式解决了这个问题:

var mongoose = require('mongoose');
var GeoJSON  = require('geojson');
var Schema   = mongoose.Schema;

var geoObjects = new Schema({
                               name : {type: String},
                               type: {
                                       type: String,
                                       enum: [
                                               "Point",
                                               "LineString",
                                               "Polygon"
                                             ]
                                      },
                                coordinates: [Number],
                                created_at: {type: Date, default: Date.now},
                                updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
geoObjects.pre('save', function(next){
   now = new Date();
   this.updated_at = now;
   if(!this.created_at) {
      this.created_at = now
   }
   next();
});

geoObjects.index({coordinates: '2dsphere'});

module.exports = mongoose.model('geoObjects', geoObjects);

以下是相关的查询:
app.post('/query/', function(req, res) {

        // Grab all of the query parameters from the body.
        var lat = req.body.latitude;
        var long = req.body.longitude;
        var distance = req.body.distance;

        var query = GeoObjects.find({'type':'Point'});

        // ...include filter by Max Distance 
        if (distance) {

            // Using MongoDB's geospatial querying features. 
            query = query.where('coordinates').near({
                center: {
                    type: 'Point',
                    coordinates: [lat, long]
                },

                // Converting meters to miles
                maxDistance: distance * 1609.34,
                spherical: true
            });
        }

        // Execute Query and Return the Query Results
        query.exec(function(err, geoObjects) {
            if (err)
                res.send(err);

            // If no errors, respond with a JSON 
            res.json(geoObjects);
        });
    });

我希望它能帮助到某人!

编辑

我提供的模式在使用LineStringsPolygons时会有一些问题。

这里是正确的模式,可以使用geoQueries

linestring-model.js:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a LineString Schema.
var linestrings = new Schema({
    name: {type: String, required : true},
    geo : {
        type : {type: String,
            default: "LineString"},
        coordinates : Array
    },
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
linestrings.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at) {
        this.created_at = now
    }
    next();
});

linestrings.index({geo : '2dsphere'});
module.exports = mongoose.model('linestrings', linestrings);

polygon-model.js

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a Polygon Schema.
var polygons = new Schema({
    name: {type: String, required : true},
    geo : {
        type : {type: String,
            default: "Polygon"},
        coordinates : Array
    },
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
polygons.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at) {
        this.created_at = now
    }
    next();
});

polygons.index({geo : '2dsphere'});
module.exports = mongoose.model('polygons', polygons);

LineString插入:

{  
    "name" : "myLinestring", 
    "geo" : {
        "type" : "LineString", 
        "coordinates" : [
            [
                17.811, 
                12.634
            ], 
            [
                12.039, 
                18.962
            ], 
            [
                15.039, 
                18.962
            ], 
            [
                29.039, 
                18.962
            ]
        ]
    }
}

多边形插入:
{  
    "name" : "Poly", 
    "geo" : {
        "type" : "Polygon", 
        "coordinates" :  [
                           [ 
                             [25.774, -80.190], [18.466, -66.118], 
                             [32.321, -64.757], [25.774, -80.190] 
                           ]
                         ]
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接