【问题标题】:How to format data for MongoEngine PointField如何为 MongoEngine PointField 格式化数据
【发布时间】:2014-05-21 08:01:05
【问题描述】:

所以我想在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

【问题讨论】:

标签: python mongodb pymongo mongoengine geojson


【解决方案1】:

我无法在此处重现您的错误。 您能否告知您正在使用哪个版本的 mongoengine?

下面是我如何实现一个简单的例子:

在我的 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 外壳上

$ 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
        ]
    }
}

问候

【讨论】:

    猜你喜欢
    • 2013-12-04
    • 2018-05-05
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多