Node.js 在Mongoose(NodeJS&x2B;MongoDB)中使用find()和地理空间坐标

Node.js 在Mongoose(NodeJS&x2B;MongoDB)中使用find()和地理空间坐标,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,猫鼬版本:3.6 节点版本:0.10 我已经试着解决这个问题好几个小时了。我想找到所有比maxDistance更接近某些坐标的文档。我试图使用MongoDB(2dsphere)的GeoJSON规范,以便以米为单位输入距离 这是我的模式“vention.js”: 这是我插入查询ctrlVenue.js的地方: var Venue = require('../models/venue.js'); VenueController = function(){}; /** GET venues li

猫鼬版本:3.6 节点版本:0.10

我已经试着解决这个问题好几个小时了。我想找到所有比maxDistance更接近某些坐标的文档。我试图使用MongoDB(2dsphere)的GeoJSON规范,以便以米为单位输入距离

这是我的模式“vention.js”:

这是我插入查询ctrlVenue.js的地方:

var Venue = require('../models/venue.js');


VenueController = function(){};

/** GET venues list ordered by the distance from a "geo" parameter. Endpoint: /venues
    Params:
        - geo: center for the list of venues - longitude, latitude (default: 25.466667,65.016667 - Oulu);
        - maxDistance: maxímum distance from the center for the list of venues (default: 0.09)
**/
exports.getVenues =function(req, res) {

    var maxDistance = typeof req.params.maxDistance !== 'undefined' ? req.params.maxDistance : 0.09; //TODO: validate
    var geo  =  typeof req.params.geo !== 'undefined' ? req.params.geo.split(',') : new Array(25.466667, 65.016667); //TODO: validate

    var lonLat = { $geometry :  { type : "Point" , coordinates : geo } };


    Venue.find({ geo: {
        $near: lonLat,
        $maxDistance: maxDistance
    }}).exec(function(err,venues){
        if (err)
            res.send(500, 'Error #101: '+err);
        else 
            res.send(venues);
        }); 
    }
当我运行代码时,我收到错误:

“错误#101:CastError:值\[对象]的数字转换失败” 对象]\“在路径\“geo\”

如果改为修改此行:

$near: lonLat,

我正确地得到了文件,但是,我不能使用米作为计量单位。 我的假设基于下表:


我见过很多使用$geometry的函数示例,但没有一个与$near一起使用。我做错了什么

我不得不使用
Mixed
类型,并添加了一些自定义验证,以确保值是数组,长度为2。我还检查了空数组,并将它们转换为
null
s,因为在
2dsphere
中使用稀疏索引时需要这样做。(Mongoose为您将数组字段设置为[],这不是有效的坐标!)


嗯,你的查询建立正确,但我不知道为什么猫鼬会大发雷霆@德里克,我也是这么想的。在我看来,这种用法非常基本,如果我是唯一一个经历过它的人,我会非常惊讶……嗨,先生,你似乎在这方面做了充分的准备。你介意看一看我的公开+50悬赏问题吗:?
$near: lonLat,
$near: geo,
var schema = new mongoose.Schema({
  location: { type: {}, index: '2dsphere', sparse: true }
});

schema.pre('save', function (next) {
  var value = that.get('location');

  if (value === null) return next();
  if (value === undefined) return next();
  if (!Array.isArray(value)) return next(new Error('Coordinates must be an array'));
  if (value.length === 0) return that.set(path, undefined);
  if (value.length !== 2) return next(new Error('Coordinates should be of length 2'))

  next();
});