Home > OS >  fast api python how to pass schemas fields to my mongo db queary?
fast api python how to pass schemas fields to my mongo db queary?

Time:10-16

Hi I am planning to use mongo db in my first api project. How can I pass any schemas fields to my mongo db query. I want to check does user mobile number exist or not during registration. here is my mongo db queary for find user mobile number:

@router.get('/details')
async def register_user():
     user = selldei_user.ads_collection.find_one({"mobile_number":"01*****"})
     user =  json.loads(json_util.dumps(user))
     user = user["mobile_number"]
     return user

here is my registration route

@router.post('/register')
async def register_user(user: schemas.User):
     user_exist = selldei_user.ads_collection.find_one({"mobile_number":"01*****"}) #here I want to pass my schemas fields 
     user_exist =  json.loads(json_util.dumps(user))
     user_exist = user["mobile_number"]
     if not  user_exist:    
        user = selldei_user.ads_collection.insert_one(user.dict()).inserted_id
    
    return {"status":"success"}

here is my schemas:

class User(BaseModel):
      first_name: str
      last_name: str
      email: str
      mobile_number: str
      password: str

CodePudding user response:

I guess, you need to use user.mobile_number like this?

async def register_user(user: schemas.User):
     user_exist = selldei_user.ads_collection.find_one({"mobile_number":user.mobile_number})
     user_exist =  json.loads(json_util.dumps(user))
     user_exist = user["mobile_number"]
     if not  user_exist:    
        user = selldei_user.ads_collection.insert_one(user.dict()).inserted_id
    
    return {"status":"success"}```
  • Related