Search code examples
pythonmongodbmongoenginefastapi

mongoengine.errors.FieldDoesNotExist: The fields "{'username', 'password'}" do not exist on the document "Users" : Error in FastAPI


I am learning FastAPI and using MongoDB. I am trying to make post request on the User object but there is some error that I am not able to figure out. The code is as follows : The User Class

class Users(Document):
    username: StringField()
    password: StringField()

class NewUsers(BaseModel):
    username: str
    password: str

And I am trying to save user as :-

@app.post('/signup')
def sign_up(new_user: NewUsers):
    user = Users(
        username=new_user.username,
        password=new_user.password
    )
    user.save()
    return {"message": "New user is successfully created!"}

Then it throws such error:

mongoengine.errors.FieldDoesNotExist: The fields "{'username', 'password'}" do not exist on the document "Users"


Solution

  • MongoEngine does not support the type hinting out of the box, you need to use "=" when setting your fields, not ":"

    class Users(Document):
        username = StringField()
        password = StringField()