0

on MongoDB , create "security" collection with a uniq index on "username" , I'm using motor.motor_asynci for working with Mongo. trying to fetch document related to "username" as following:

from motor.motor_asyncio import AsyncIOMotorClient


def load_config() -> dict:
    with open('config/config.yml') as yaml_file:
        conf = yaml.load(yaml_file.read(), Loader=yaml.SafeLoader)
    return conf


CONF = load_config()


## Mongo
DB_CLIENT = AsyncIOMotorClient(
    host=CONF.get("databases", dict())["mongo"]["HOST"],
    port=CONF.get("databases", dict())["mongo"]["PORT"],
    username=CONF.get("databases", dict())["mongo"]["USER"],
    password=CONF.get("databases", dict())["mongo"]["PASSWORD"],
)


DB = DB_CLIENT[CONF.get("databases", dict())["mongo"]["NAME"]]



cursor_user =  DB.security.find({'username': "someuser"}) 
for doc in  cursor_user:
   print (doc)

getting "TypeError: 'AsyncIOMotorCursor' object is not iterable"

as this collection has uniq index on the search key, i also tried find_one but also not working:


user =  DB.security.find_one({'username': "someuser"}) 
print(user)


getting:

<Future pending cb=[run_on_executor.<locals>._call_check_cancel() at /usr/local/lib/python3.8/site-packages/motor/frameworks/asyncio/__init__.py:80]>
Florian
  • 2,562
  • 5
  • 25
  • 35
AviC
  • 354
  • 1
  • 5
  • 15

1 Answers1

1

I create a function in my config file and import it to routes file, Note, it also suppress _id coming from Mongo by default

async def search_user(username: str):
    user = await security_collection.find_one({"username": username} ,{"_id":0})
    return user


from routing :

@security_router.get("/find_username")
async def search_username(username: str):
    user = await search_user(username)
    print("User main",user)
    if user:
        return ResponseModel(
            "User: {} exist ".format(user), "Something"
        )
    return ErrorResponseModel(
        "An error occurred", 404, "User {0} doesn't exist".format(username)
    )

Florian
  • 2,562
  • 5
  • 25
  • 35
AviC
  • 354
  • 1
  • 5
  • 15