本文介绍了如何格式化MongoEngine PointField的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想对mongodb中的位置数据做一些实验,所以我写了一些python代码来生成一些测试数据.
不幸的是,文档位于 http://docs.mongoengine.org/apireference.html# mongoengine.fields.PointField 并未明确说明如何格式化输入.

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

尝试存储包含lng/lat的列表失败:

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)

传递geoJSON文档会导致相同的错误:

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)

应如何设置格式?

注意:之前曾问过类似的问题,但答案无济于事:

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

推荐答案

我无法在此处重现您的错误.您能否告知您正在使用哪个版本的mongoengine?

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:

在我的模型上.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 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]}

在我的数据库上

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

致谢

这篇关于如何格式化MongoEngine PointField的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:47