0

If I pass an invalid row, it throws an exception. I would like it to return NULL so I can use it to further process the rest of my scripts.

module_id = module_id

mongo_document = mongo_collection.find_one({ '_id': '%s' % module_id}, { '_id':0, 'svn_path':1 })
myvar = mongo_document
for key, value in myvar.iteritems():
    print value
3
  • 1
    catch the Exception? Commented Jul 23, 2013 at 17:06
  • 1
    Which exception is actually being raised? it looks like find_one might return None already if no matching collections are found. github.com/mongodb/mongo-python-driver/blob/master/pymongo/…, is myvar None? and you are trying to call iteritems on None? Commented Jul 23, 2013 at 17:14
  • I'm an idiot, you're right it does return none. I didnt check for this, I went ahead and attempted to print the value without checking. Commented Jul 23, 2013 at 17:17

1 Answer 1

1

Actually your problem isn't in the find_one function. when you ask for a value that doesnt exist its returns a None value to python, my guess that your exception is actually in the for loop. so i would do something like that:

module_id = module_id

mongo_document = mongo_collection.find_one({ '_id': '%s' % module_id}, { '_id':0, 'svn_path':1 })
myvar = mongo_document
if myvar is not None:
   for key, value in myvar.iteritems():
       print value
eilf:
   print "sorry i could find that id"
Sign up to request clarification or add additional context in comments.

2 Comments

yea that was it, I forgot to check myvar
Yep, i have to wait a few more mins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.