1

我有一个集合,每个文档都有一组字段值。其中之一称为“坐标”。现在,当我在数据库中查询该字段不为空的元素时,它会返回我期望的正确值。

但是我不时在python(Pymongo)中遇到这个错误:

if not doc['coordinates']
TypeError: 'NoneType' object has no attribute '__getitem__'

这似乎意味着它遇到了没有字段“坐标”的记录。我已经创建了具有此字段的文档并且应该存在。

不过,我想知道如何处理此错误并防止此错误终止我的程序。

这就是我找到适当查询的方式:

 cursor = collection.find(
                { "$and" : [
                    {"term": {"$in": events}}, 
                    { "$or" : [
                            {"coordinates" : {"$ne": None}}, 
                            {"place" : {"$ne" : None}}
                    ]}
                ]}, 
            {"term" : 1, "coordinates" : 1, "place" : 1, "time_normal" : 1}, tailable = True, timeout = False )

然后我遍历返回的查询,如下所示:

while cursor.alive:
    try:
        doc = cursor.next()

        CODE IS HERE TO QUERY DB


    except StopIteration:
        pass

谢谢

4

4 回答 4

2

您在示例中获得 aTypeErrorAttributeError在 nickmilon 提供的示例中获得 a 的原因是因为您用来获取您的查询doc没有找到任何内容(因此是 a NoneType)。检查您的查询以确保您确实从您的收藏中获取了东西。

不过,nickmilon 提供的答案应该为您提供您所追求的错误处理。

于 2012-12-16T15:56:18.147 回答
1

Eric is right, for some reason your doc is None. Could you post here the code you are using for find and how you process the cursor returned from find ?

于 2012-12-16T16:38:09.670 回答
1

您可以尝试: doc.get('coordinates') 如果字段不存在,它将返回 None ,如果存在则返回其值

于 2012-12-16T15:27:07.177 回答
0

我能够通过在异常块中包含 TypeError 来处理此错误,如下所示:

                try:                                               
                    if not doc['coordinates']:
                        CODE HERE

                    else: 
                        CODE HERE

                except (TypeError):
                    pass
于 2012-12-16T20:35:21.883 回答