gpt4 book ai didi

node.js - 在mongodb中保存位置

转载 作者:可可西里 更新时间:2023-11-01 09:11:57 26 4
gpt4 key购买 nike

我试图在我的 2dsphere 模型中保存坐标。

这是我的模型:

var userSchema   = new Schema({
email: {
type: String,
required: true,
unique: true
},
...
loc: {
type: {
type: "String",
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
},
coordinates: [Number]
}

});
userSchema.index({'loc': '2dsphere'});
const User = mongoose.model('User', userSchema);
module.exports = User

我保存新数据的查询格式如下:

email:eu@vc.com
password:t12345
name:Igor
type:true
loc:{
coordinates: [-43.306174, -22.844279]
}

这是我收到的错误:

{
"code": 16804,
"index": 0,
"errmsg": "location object expected, location array not in correct format",
"op": {
"email": "eu@vc.com",
"password": "t12345",
"name": "Igor",
"_id": "5a311c016d15fc235895bef3",
"created_at": "2017-12-13T12:24:33.493Z",
"loc": {
"coordinates": [],
"type": "Point"
},
"type": true,
"__v": 0
}
}

最佳答案

您可能在集合中同时拥有 2d 和 2dsphere 索引。

error下面表示您有一个二维索引。

"errmsg": "location object expected, location array not in correct format",

因此,当您尝试保存球坐标 ({"loc": {"coordinates": [23, 25],"type": "Point"}) 时,mongodb 会出现错误建立索引。

下面的错误 ( first part & second part) 表明您有一个二维球体索引。

"errmsg": "Can't extract geo keys: {...loc: { coordinates: [23, 25] }} unknown GeoJSON type

因此,当您更改为 {"loc": {"coordinates": [23, 25] }} 时,二维球体索引无法构建。

您可以验证索引。 db.users.getIndexes()

删除 2d 索引(仍然存在是为了向后兼容)。二维球体索引支持传统坐标(例如 {"loc":[23, 25]})和地理坐标。

db.users.dropIndex( "loc_2d" ) 

这应该在 2d sphere index 为集合重建索引时起作用。

如果上述解决方案不起作用,请删除集合并重新开始。

db.users.drop()

关于node.js - 在mongodb中保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47795314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com