How to format data for MongoEngine PointField

*爱你&永不变心* 提交于 2019-12-07 22:29:45

问题


So I wanted to do some experiments with location data in mongodb, so I wrote some python code to generate some testing data.
Unfortunately the documentation at http://docs.mongoengine.org/apireference.html#mongoengine.fields.PointField isn't explicit about how to format the input.

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

Trying to store a list containing the lng/lat fails:

>>> a = Location(coord=[1,2])
>>> a.save()
mongoengine.errors.OperationError: Could not save document (location object expected, location array not in correct format)

Passing a geoJSON document results in the same erro:

>>> 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)

How should this be formatted?

NOTE: a similar question was asked before, but the answer wasn't helpful: Mongoengine PointField gives location object expected, location array not in correct format error


回答1:


I could not reproduce your error here. Can you inform which version of mongoengine are you working with?

Here is how I could implement a simple example:

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

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

on my DB

> db.point_field_example.findOne()
{
    "_id" : ObjectId("5345a51dbeac9e0c561b1892"),
    "point" : {
        "type" : "Point",
        "coordinates" : [ 
            -47, 
            -15
        ]
    }
}

Regards



来源:https://stackoverflow.com/questions/22940168/how-to-format-data-for-mongoengine-pointfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!