我在猫鼬版本3.8.3中使用mongoDB$nearSphere方法来查找附近的位置。
mongoose.models['Event']
.find({ loc :
{
$nearSphere :
{
$geometry : loc,
$maxDistance : 100000
}
}
})
.limit(100)
.exec(function (err, events)
{
console.log(err)
...
}
事件方案中的 loc 字段具有"2dsphere"索引:
var EventSchema = new Schema
({
...
loc:
{
type: { type: String },
coordinates: { type: [Number], index: '2dsphere' }
},
...
});
变量 loc 的类型为"点"。一个例子是:
{ coordinates: [ 12.93598683338508, 48.43299197266921 ], type: 'Point' }
执行上述搜索语句后,我总是收到错误:
2013-12-27T08:46:57.997102+00:00 app[web.1]: { message: 'Cast to number failed for value "Point" at path "__QueryCasting__"',
2013-12-27T08:46:57.997105+00:00 app[web.1]: name: 'CastError',
2013-12-27T08:46:57.997107+00:00 app[web.1]: type: 'number',
2013-12-27T08:46:57.997108+00:00 app[web.1]: value: 'Point',
2013-12-27T08:46:57.997110+00:00 app[web.1]: path: '__QueryCasting__' }
有人可以弄清楚为什么会出现此错误以及如何解决它吗?
这看起来像猫鼬中的错误。我已提交一个问题:https://github.com/LearnBoost/mongoose/issues/1874
我有两个解决方法建议。
我通过更改以下内容修补了猫鼬/lib/query.js:
} else if (('$near' == geo || '$geoIntersects' == geo) &&
自
} else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) &&
它对我有用(猫鼬 3.8.3)。
其次,您可以将查询作为"旧版"坐标对运行(您需要将 maxDistance 转换为弧度)。http://docs.mongodb.org/manual/reference/operator/query/nearSphere/
猫鼬有一个内置的方法称为near()
,它接受一个GeoJSON Point进行球形地理空间查询。
从文档中:
指定$near或$nearSphere条件
因此,而不是:
mongoose.models['Event']
.find({ loc :
{
$nearSphere :
{
$geometry : loc,
$maxDistance : 100000
}
}
}).limit(100).exec(function (err, events) { ... });
试试这个:
mongoose.models['Event']
.near('loc', {
center: loc,
maxDistance : 100000
}).limit(100).exec(function (err, events) { ... });
这不是猫鼬中的错误,你应该在"loc.坐标"上做find(),而不仅仅是'loc',因为这是2dsphere索引所在的字段。现在,即使猫鼬在没有失败的情况下投射此查询,mongodb 服务器也会返回错误,因为您尝试在没有地理索引的字段上运行$nearSphere。FWIW 1 衬垫修复将在猫鼬的下一个次要版本中,但您还应该更改查询代码。