Mongodb does not return query correctly

Asked

Viewed 37 times

0

I have the following code:

from pymongo import MongoClient

class ConectaMongodb:

    def conecta(self):

        client = MongoClient('mongodb://localhost:27017')
        db = client.starwars_api
        return db

    def search_name(self, name):   

        c = ConectaMongodb()
        conn = c.conecta()

        posts = conn.planetas

        try:
            name_posts = posts.find({'name': name.title()})
            for post in name_posts:
                print('Id: {0} \nNome: {1} \nClima: {2} \nTerreno: {3} \nAparições em filmes: {4} vezes \n'
                    .format(post['_id'], post['name'], post['climate'], post['terrain'], post['counter']))    

        except:
            print('Nenhum planeta foi encontrado.')

When I run the method as follows:

conn = ConectaMongodb()
conn.conecta()
conn.search_name('Tatooine')

My return is:

id: 5cdceb8732e8b889be669fc4 Name: Tatooine Climate: arid Land: Land Movie appearances: 5 times

But when the method receives an error value, it returns nothing:

conn = ConectaMongodb()
conn.conecta()
conn.search_name('Tatone')

1 answer

0

Instead of using

except: print('Nenhum planeta foi encontrado.')

uses

except ValueError: print('Nenhum planeta foi encontrado.')

  • the problem still persists

  • He makes no mistake when he doesn’t find?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.