如何为MongoEngine的PointField格式化数据

4 投票
1 回答
2909 浏览
提问于 2025-04-18 01:52

我想在mongodb中做一些关于位置数据的实验,所以写了一些python代码来生成测试数据。
可惜的是,http://docs.mongoengine.org/apireference.html#mongoengine.fields.PointField的文档没有明确说明输入应该怎么格式化。

class Location(db.Document):
    coord = db.PointField(required=True)  # GeoJSON

尝试存储一个包含经度和纬度的列表时失败了:

>>> 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给出了位置对象,期望的格式是位置数组不正确的错误

1 个回答

4

我这边没法重现你遇到的错误。你能告诉我你使用的是哪个版本的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
        ]
    }
}

祝好

撰写回答