【发布时间】:2016-07-17 01:26:40
【问题描述】:
如果假设距离当前纬度/经度坐标 10 公里,我正在尝试在 Mongoose 中加载文档。
假设我有这个对象:
{
lat: -33.9493992,
lon: 151.1114885
}
在我的 Mongoose 数据库中,我有一个集合,这个集合中的每个文档也有保存 lat-lon 键。如何只抓取距给定坐标一定距离的条目?
例如,我只想抓取距离上述坐标最远 10 公里的文档。
我将不胜感激。
编辑: 我的代码:
初始化模型:
var schema = new mongoose.Schema({
title: String,
title: String,
coordinates: {
type: [ Number ],
default: [0, 0],
index: '2dsphere'
}
});
global.models.Point = mongoose.model('Point', schema);
以及试图在模型中找到的代码: router.route('/points/:lat/:lon') .get(函数 (req, res) { console.log('lat:' + req.params.lat + 'lon:' + req.params.lon);
global.models.Point.find({
coordinates: {
$near: {
$maxDistance: 100 / 111.12,
$geometry: {
type: 'Point',
coordinates: [req.params.lon, req.params.lat]
}
}
}
}, function (err, res) {
if (err) {
return console.log(err);
}
console.log(res);
});
});
存储在数据库集合中的对象:
{
"_id" : ObjectId("56ea103eefedec96b6d4b203"),
"title" : "Some title",
"coordinates" : [
5.2260167,
52.3500607
]
}
【问题讨论】:
-
阅读文档。
$nearSphere。你不想要单独的属性。文档将告诉您文档应该如何存储数据。
标签: node.js mongodb mongoose odm