我想在用户模型中保存位置的经度/纬度,并使用$geoNear
查询它。我查看了几乎所有相关主题的页面,但仍然不确定如何 1)适当地创建模型和2)如何进行查询。
以下是我的模型部分:
loc: {
//type: 'Point', // see 1
//type: String, // see 2
coordinates: [Number],
index: '2dsphere' // see 3
},
@1: 根据文档,如果我想存储一个点,类型必须为“Point”,但它会抛出异常。
TypeError: Undefined type `Point` at `loc`
Did you try nesting Schemas? You can only nest using refs or arrays.
这是有道理的,因为我猜它应该是一个字符串
@2:这不会立即报错,但当我尝试存储用户时,会出现以下错误:
name: 'ValidationError',
errors:
{ loc:
{ [CastError: Cast to String failed for value "[object Object]" at path "loc"]
@3:如果我想创建这样的索引,我会收到错误提示:
TypeError: Undefined type `2dsphere` at `loc.index`
Did you try nesting Schemas? You can only nest using refs or arrays.
因此,我尝试将索引存储到我认为更合适的位置,如下所示:
userSchema.index({'loc': '2dsphere'});
当我尝试保存新用户时,出现以下错误:
- { [MongoError: Can't extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }]
name: 'MongoError',
message: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }',
ok: 1,
n: 0,
code: 16572,
errmsg: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }',
writeConcernError:
{ code: 16572,
errmsg: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }' } }
MongoError: Can't extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }
当我将数据库中的模型更新为
$geoNear
命令时,我像这样更新了我的用户:loc: {coordinates: [-73.97, 40.77]}
并且可以通过以下方式成功查询:
mongoose.model('users').db.db.command({
"geoNear": users,
"near": [
<latitude>,
<longitude>
],
"spherical": true,
"distanceMultiplier": 6378.1, // multiplier for kilometres
"maxDistance": 100 / 6378.1, // every user within 100 km
"query": { }
我使用了 db.command
,因为根据我所读的资料,在使用 find()
时 $geoNear
是不可用的。
到目前为止,我尝试过的所有方法都没有成功,所以我的问题是:
- 我的 mongoose 模型应该是什么样子的?
- 如何将用户及其位置存储在我的数据库中?
任何帮助都将不胜感激!