Node.js mongoose 3.8.3中mongoDB近球方法中的CastError
在Mongoose3.8.3版中,我使用mongoDB$nearSphere方法查找附近的位置Node.js mongoose 3.8.3中mongoDB近球方法中的CastError,node.js,mongodb,mongoose,geospatial,geo,Node.js,Mongodb,Mongoose,Geospatial,Geo,在Mongoose3.8.3版中,我使用mongoDB$nearSphere方法查找附近的位置 mongoose.models['Event'] .find({ loc : { $nearSphere : { $geometry : loc, $maxDistance
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__' }
有人能找出这个错误出现的原因和解决方法吗?这看起来像猫鼬中的一个bug。我提出了一个问题: 我有两个解决办法要建议 我通过更改以下内容修补了mongoose/lib/query.js:
} else if (('$near' == geo || '$geoIntersects' == geo) &&
到
它对我很有效(猫鼬3.8.3)
其次,可以将查询作为“传统”坐标对运行(需要将maxDistance转换为弧度)。
Mongoose为此有一个内置方法,称为,它接受用于球形地理空间查询的GeoJSON点 从文档中: 指定$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) { ... });
这在mongoose中并不是一个真正的bug,您应该在'loc.coordinates'上执行find(),而不仅仅是'loc',因为这是2dsphere索引所在的字段。现在,即使mongoose在没有失败的情况下强制执行此查询,mongodb服务器也会返回一个错误,因为您试图在没有地理索引的字段上运行$nearSphere。FWIW mongoose的下一个小版本将提供1行程序修复,但您也应该更改查询代码。所以我也有同样的问题,这里发生了什么。Mongoose现在是3.8.8,这个问题是否已解决?我还在吃。实际上,我在MongoDB shell中运行了该命令,并且运行得很好。。猫鼬不起作用
mongoose.models['Event']
.near('loc', {
center: loc,
maxDistance : 100000
}).limit(100).exec(function (err, events) { ... });