2014-04-08 29 views
1

所以我想用mongodb中的位置數據做一些實驗,所以我編寫了一些python代碼來生成一些測試數據。
不幸的是,在http://docs.mongoengine.org/apireference.html#mongoengine.fields.PointField文檔不明確有關如何格式化輸入。如何爲MongoEngine 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

+0

所以這可能是由於燒瓶mongoengine不支持GeoFields:https://flask-mongoengine.readthedocs.org/en/latest/ –

回答

2

我無法在這裏重現你的錯誤。 你能告訴你在使用哪種版本的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上對我的DB外殼

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

問候