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