How to format data for MongoEngine PointField

柔情痞子 提交于 2019-12-06 05:56:33

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

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