【发布时间】:2016-05-10 22:24:29
【问题描述】:
我正在使用 node.js 和猫鼬。我的数据库中有 4 个对象,坐标为 lng/lat。在现实生活中,这些位置彼此相距 1 或 2 英里。
module.exports.locationsListByDistance = function(req, res) {
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var point = {
type: "Point",
coordinates: [lng, lat]
};
var geoOptions = {
spherical: true,
maxDistance: 20 / 3963,
num: 10
};
Loc.geoNear(point, geoOptions, function(err, results, stats) {
var locations;
console.log('Geo Results', results);
console.log('Geo stats', stats);
if (err) {
console.log('geoNear error:', err);
sendJsonResponse(res, 404, err);
} else {
locations = buildLocationList(req, res, results, stats);
sendJsonResponse(res, 200, locations);
}
});
};
这是我的代码。当Loc.geoNear 运行时,在回调函数results 中返回一个空数组。我可以让它真正返回对象的唯一方法是设置maxDistance: 2500,然后它将检索2个具有荒谬距离的对象。
现在显然,2500 是一个巨大的数字,这意味着零。我需要彼此相距 20 英里,这就是为什么我通过 20 / 3963 转换为弧度,但生成的 maxDistance 是如此之小,以至于 mongo 什么也没有返回。有任何想法吗?
编辑 1 (添加文档)
{
"_id": {
"$oid": "5714204af42b2b9004313d7c"
},
"name": "Starcups",
"address": "125 High Street, Reading, RG6 1PS",
"rating": 3,
"facilities": [
"Hot drinks",
"Food",
"Premium wifi"
],
"coords": {
"lng": -84.135166,
"lat": 34.190996
},
"openingTimes": [
{
"days": "Monday - Friday",
"opening": "7:00am",
"closing": "7:00pm",
"closed": false
},
{
"days": "Saturday",
"opening": "8:00am",
"closing": "5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"author": "Kenny Hall",
"rating": 5,
"timestamp": "13 April 2016",
"reviewText": "What a great place. I can't say enough good things about it."
},
{
"author": "Charlie Chaplin",
"rating": 3,
"timestamp": "16 June 2015",
"reviewText": "It was okay. Coffee wasn't great, but the wifi was fast."
}
]
}
EDIT 2(添加模型/模式)
var mongoose = require('mongoose');
var reviewSchema = new mongoose.Schema({
author: String,
rating: {
type: Number,
required: true,
min: 0,
max: 5
},
reviewText: String,
createdOn: {
type: Date,
"default": Date.now
}
});
var openingTimeSchema = new mongoose.Schema({
days: {
type: String,
required: true
},
opening: String,
closing: String,
closed: {
type: Boolean,
required: true
}
});
var locationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: String,
rating: {
type: Number,
"default": 0,
min: 0,
max: 5
},
facilities: [String],
// Always store coordinates longitude, latitude order
coords: {
type: [Number],
index: '2dsphere'
},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
【问题讨论】:
-
你有什么类型的索引? 2d 还是 2dsphere?
-
另外请发布示例 MongoDB 文档
-
@Saleem 这是一个 2dsphere。我将使用文档编辑帖子。
-
@Saleem 很高兴知道这些差异,谢谢。但是,如果您在下面查看我的 cmets 到 Anonymous-SOS 答案,Mongod 仍然会返回不切实际的值。