1

I am a beginner in python. I am trying to connect to a database and match user entered values.

if staff==<user entered value>and paper==<user entered value>:
   test=db.staff.find({"staff":<user entered value>,"paper":<user entered value>})
   print(test.get('staff'))
   print(test.get('paper'))

if test has no value,I get error when the database returns no value

4
  • It seems like you are using mongodb. Right? Commented Aug 5, 2015 at 7:35
  • yes , I am using mongodb Commented Aug 5, 2015 at 7:37
  • from where do you get the value of staff in the first place? Commented Aug 5, 2015 at 7:38
  • staff is the overall collection of all the staff Commented Aug 5, 2015 at 7:40

2 Answers 2

1

When your db.staff.find_one({"staff":<user entered value>,"paper":<user entered value>}) doesn't match anything in your database the value of test will be None. And a None object does not have a .get() method.

You may need to use an if statement to check it before running .get() method

Sign up to request clarification or add additional context in comments.

2 Comments

This will fail because .find returns a cursor not document
His question was about dealing with empty test. In your case he can loop over the cursor or use find_one()
1
  • You should use the .count to check if your query returns any result.
  • .find returns an instance of Cursor so you have to loop over your query result.

    if staff==<user entered value>and paper==<user entered value>:
        test = db.staff.find({"staff":<user entered value>,"paper":<user entered value>})
        if(test.count()):
            for doc in test:
                print(test['staff'])
                print(test['paper'])
    

If staff and paper are unique in your collection use the find_one method.

if staff==<user entered value>and paper==<user entered value>:
    test = db.staff.find_one({"staff":<user entered value>,"paper":<user entered value>})
    if(test):
        print(test['staff'])
        print(test['paper'])

Comments

Your Answer

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