简体   繁体   English

MongoDB - 对不存在的字段进行错误处理

[英]MongoDB - Error handling for non-existent field

I have a collection with a set of field values for each document. 我有一个集合,每个文档都有一组字段值。 One of these is called 'coordinates'. 其中一个称为“坐标”。 Now when I'm querying the DB for and for elements that are not null for this field, it returns the right values as I'm expecting. 现在,当我查询数据库以及该字段的非空元素时,它会返回正确的值,正如我所期望的那样。

However I run into this error now and then in python (Pymongo): 但是我现在遇到这个错误然后在python(Pymongo):

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

This seems to imply that it has come across a record where there is no field 'coordinates'. 这似乎意味着它已经遇到了没有场“坐标”的记录。 I've created the document to have this field and should exist. 我已经创建了这个字段并且应该存在的文档。

I want to know though, how can I handle this error and to prevent this error from terminating my program. 我想知道,我怎么能处理这个错误并防止这个错误终止我的程序。

This is how I find the appropriate queries: 这是我找到适当查询的方式:

 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 )

I then iterate through the returned queries, as: 然后我遍历返回的查询,如下所示:

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

        CODE IS HERE TO QUERY DB


    except StopIteration:
        pass

Thanks 谢谢

The reason you're getting a TypeError in your example and an AttributeError in the example that nickmilon supplied is because the query that you're using to get your doc is not finding anything (and is therefore a NoneType ). 你得到一个原因TypeError在你的榜样和AttributeError在nickmilon提供的例子是因为你使用,让您的查询doc没有找到任何东西(因此是NoneType )。 Check your query to make sure that you're actually getting things out of your collection. 检查您的查询,以确保您实际上从您的收藏中获取东西。

The answer that nickmilon supplies should give you the error handling you're after, though. 但是,nickmilon提供的答案应该会为您提供错误处理。

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

Eric is right, for some reason your doc is None. Eric是对的,出于某种原因你的doc是None。 Could you post here the code you are using for find and how you process the cursor returned from find ? 你能在这里发布用于查找的代码以及如何处理从find返回的光标吗?

I was able to handle this error by including the TypeError in the exception block, as: 我能够通过在异常块中包含TypeError来处理此错误,如下所示:

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

                    else: 
                        CODE HERE

                except (TypeError):
                    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM