Node.js Mongoose地理查询未返回正确的结果
我试图查询一个数据库,在该数据库中,我存储了某些坐标附近的位置坐标,并指定了maxDistance。 我在官方mongo文档中读到,maxDistance以米为单位。 集合架构如下所示:Node.js Mongoose地理查询未返回正确的结果,node.js,mongodb,mongoose,geolocation,Node.js,Mongodb,Mongoose,Geolocation,我试图查询一个数据库,在该数据库中,我存储了某些坐标附近的位置坐标,并指定了maxDistance。 我在官方mongo文档中读到,maxDistance以米为单位。 集合架构如下所示: var BranchSchema = new Schema({ parentId: { type: Schema.Types.ObjectId, required: 'The ID of the parent is required.', index: true }, name: {
var BranchSchema = new Schema({
parentId: {
type: Schema.Types.ObjectId,
required: 'The ID of the parent is required.',
index: true
},
name: {
type: 'String',
required: 'The branch name is required.'
},
location: {
type: [Number],
index: {
type: '2dsphere'
}
}
});
Branch.where('location').near({
center: [lat, long],
maxDistance: proximity,
spherical: true
}).exec(function (err, branches) {
if (err) {
return res.status(400)
.send({
message: errors.getErrorMessage(err)
});
}
return res.json(branches);
});
我插入了一份包含以下信息的文件:
{
"parentId" : ObjectId("54ee08c2d903aca72291f120"),
"name" : "Branch1",
"_id" : ObjectId("54ee422809f242122744990c"),
"location" : [
33.377796,
35.480911
]
}
然后我尝试查询lat=33.901948和long=35.576797,最大距离为5。
我在网上使用了一个在线工具(),它给出了lat=33.901948和long=35.576797之间的距离,lat=33.377796和long=35.480911之间的距离为58公里,明显大于5米,查询仍然返回结果,但不应该返回
mongoose查询如下:
var BranchSchema = new Schema({
parentId: {
type: Schema.Types.ObjectId,
required: 'The ID of the parent is required.',
index: true
},
name: {
type: 'String',
required: 'The branch name is required.'
},
location: {
type: [Number],
index: {
type: '2dsphere'
}
}
});
Branch.where('location').near({
center: [lat, long],
maxDistance: proximity,
spherical: true
}).exec(function (err, branches) {
if (err) {
return res.status(400)
.send({
message: errors.getErrorMessage(err)
});
}
return res.json(branches);
});
提前谢谢事实上,我在你的问题上看到了一些错误 1-索引
- 2dsphere index if specifying a GeoJSON point
- 2d index if specifying a point using legacy coordinates.
您的架构使用传统坐标字段。这不是一个GeoJSON字段。因为GeoJSON必须包含一个坐标类型值,如下所示:
location: {
'type': { type: String, default: 'Point' },
coordinates: [Number]
}
如果您想使用传统坐标字段,则应使用2d
索引
2-lat.和lng订单。
你的密码必须
另一方面,如果你想使用传统的2d索引,你可以使用
上述代码有一个$maxDistance
参数,用于指定半径。我想你应该退房。因为你必须考虑下面的线以找到5米的接近度。< /P>
5米=(5/6371000)地球半径
因此,我认为以下代码有效
Branch.where('location').near({
center: [long, lat],
maxDistance: 5/6371000,
spherical: true
}).exec(function (err, branches) {
if (err) {
return res.status(400)
.send({
message: errors.getErrorMessage(err)
});
}
return res.json(branches);
});
或
我希望这有帮助,祝你好运 这似乎是猫鼬的一个bug,看看吧,请注意,中心被指定为[long,lat]而不是[lat,long]
Branch.find(
{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 5/6371000 }},
function (err, branches) {
if (err) {
return res.status(400)
.send({
message: errors.getErrorMessage(err)
})
}
return res.json(branches);
}
)