所以我想在mongodb中对位置数据做一些实验,所以我写了一些python代码来生成一些测试数据。
不幸的是,http://docs.mongoengine.org/apireference.html#mongoengine.fields.PointField上的文档没有明确说明如何格式化输入。
class Location(db.Document):
coord = db.PointField(required=True) # GeoJSON
尝试存储包含lng / lat的列表失败:
>>> a = Location(coord=[1,2])
>>> a.save()
mongoengine.errors.OperationError: Could not save document (location object expected, location array not in correct format)
传递geoJSON文档会产生相同的错误:
>>> b = Location(coord={ "type" : "Point" ,"coordinates" : [1, 1]})
>>> b.save()
mongoengine.errors.OperationError: Could not save document (location object expected, location array not in correct format)
如何格式化?
注意:之前曾问过类似的问题,但答案没有帮助:Mongoengine PointField gives location object expected, location array not in correct format error
答案 0 :(得分:2)
我无法在此处重现您的错误。 你能告诉你使用哪种版本的mongoengine吗?
以下是我如何实现一个简单的例子:
on my models.py
class PointFieldExample(Document):
point = PointField()
name = StringField()
def toJSON(self):
pfeJSON = {}
pfeJSON['id'] = str(self.id)
pfeJSON['point'] = self.point
pfeJSON['name'] = str(self.name)
return pfeJSON
Django shell上的
$ python manage.py shell
>>> from mongoengine import *
>>> from myAwesomeApp.app.models import PointFieldExample
>>> pfe = PointFieldExample()
>>> pfe.point = 'random invalid content'
>>> pfe.toJSON()
{'id': 'None', 'name': 'None', 'point': 'random invalid content'}
>>> pfe.save()
ValidationError: ValidationError (PointFieldExample:None) (PointField can only accept lists of [x, y]: ['point'])
>>> pfe.point = [-15, -47]
>>> pfe.save()
<PointFieldExample: PointFieldExample object>
>>> pfe.toJSON()
{'id': '5345a51dbeac9e0c561b1892', 'name': 'None', 'point': [-15, -47]}
我的数据库
> db.point_field_example.findOne()
{
"_id" : ObjectId("5345a51dbeac9e0c561b1892"),
"point" : {
"type" : "Point",
"coordinates" : [
-47,
-15
]
}
}
此致