【问题标题】:Using find() with geospatial coordinates in Mongoose (NodeJS+MongoDB)在 Mongoose (NodeJS+MongoDB) 中使用带有地理空间坐标的 find()
【发布时间】:2013-07-10 10:34:33
【问题描述】:

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

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

这是我的架构“venue.js”:

var db = require('mongoose'),
    Schema = db.Schema,
    ObjectId = Schema.ObjectId;

var venueSchema = new Schema({
    geo: { type: [Number], index: '2dsphere'},
    city: String,
    name: String,
    address: String
});


module.exports = db.model('Venue', venueSchema);

这是我插入查询 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: 值转换为数字失败”[object 对象]\" 在路径 \"geo\""

如果我改为修改这一行:

$near: lonLat,

$near: geo,

我正确获取了文件,但是我不能使用米作为度量单位。 我的假设基于下表:http://docs.mongodb.org/manual/reference/operator/query-geospatial/

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

【问题讨论】:

  • 嗯,您的查询建立正确,但我不知道为什么猫鼬会大吃一惊!
  • @Derick 这就是我的想法。这种用法在我看来是如此基础,如果我是唯一一个经历过它的人,我会感到非常惊讶......

标签: node.js mongodb mongoose


【解决方案1】:

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

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();
});

【讨论】:

猜你喜欢
  • 2019-09-23
  • 2011-10-25
  • 2014-04-29
  • 2016-05-01
  • 1970-01-01
  • 2011-11-12
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多