Package: graphene-mongodb
GrapheneMongoGrapheneMongodb is a library that integratesGraphenewithMongoEngineExamplesGiven that mongoengine Document:classUser(Document):username=StringField()creation_date=DateTimeField()favourite_color=ListField(StringField())To generate a graphene schema for that Document we create a class that is subclass of graphene_mongodb.MongoSchema, or we can also just call it passing the model as first argument:fromgraphene_mongodbimportMongoSchemaclassUserSchema(MongoSchema):model=User# ORUserSchema=MongoSchema(User)The schema now it's generated. Now it's necessary to create a graphene object Query:importgrapheneclassQuery(graphene.ObjectType):user=UserSchema.singleschema=graphene.Schema(query=Query)# now we can do the query:result=schema.execute("""query Data {user(username: "John") {idusername}}""")You may notice the UserSchema.single attribute in the example above, the class UserSchema has many other attributes. All they are explained below:AttributeDescriptionsingleWe use single we want that the query result be a unique result. That's the same that make the query in mongoengine calling .first() to get the first object that matches the query.listList is used when we want a list of the documents that matches the query.modelThat's easy, this attribute stores the original Document of mongoengine that you created.fieldsThis field is more consult, you can use the fields that was converted from mongoengine to graphene. For instance, in our UserSchema class the attribute field will be a dict like this: {'username': graphene.String}mutationMutate is the attribute that we use when creating Mutations with graphene. See more inMutationsMutationsSometimes we need to save new data in mongodb instead of doing queries. Mutations do that job.
Let's use again theUserSchemathat we created in the examples. As before we create a graphene object called Query to handle the query, and we now need to do the same to a Mutation:classMutation(graphene.ObjectType):create_user=UserSchema.mutateschema=graphene.Schema(query=Query,mutation=Mutation)Notice that we updated the variable schema to have a mutation object too.
Now we can do the mutation query and create a new user in our database:result=schema.execute("""mutation testMutation {createUser(username:"John") {person {idusername}}}""")We pass the attributes that we want to save in the 'params', as we did in "...createPerson(username:"John")..."In this example GrapheneMongodb handled the save of the object for you, but sometimes you need to make validations before actually saving the object to the database. How you can do that is explained next.Verifications before saveTo use your own function for saving, you need to create a function in the MongoSchema class calledmutate. Said that, lets update our UserSchema as follows:classUserSchema(MongoSchema):model=User@staticmethoddefmutate(args,context):new_user=User(**args)new_user.creation_date=datetime.now()new_user.save()returnnew_userThere's not many rules here, you only need to be sure that the method receives two parameters, has the static method decorator and returns the instance of the object.Thecontextparameter has the request object of the framework that you're using. If you're using flask for instance, that parameter will be theflask global request.Operators in queryMongoengine offers many kinds of operators to use as 'in', 'gte', etc. See all operators inmongoengine documentation. With GrapheneMongodb you can use them in your query:result=schema.execute("""query Data {user(username_Icontains: "John", creationDate_Gte:"1997-04-28", favouriteColor_In:["red"]) {idusername}}""")The best is that they are all supported by GrapheneMongodb.Validate permissions to do queries and mutationsTo validate if a user can access some field you can create an attribute calledvalidator:classUserSchema(MongoSchema):model=Userdefvalidator(model,fields,query,special_params):if'not_alowed_field'infields:raiseException('Unauthorized Access')When a validator function exists, GrapheneMongodb will call it in every query or mutation of the respective schema.
Just be sure to raise a exception that graphene will be responsible to send back to graphql client in the frontend.TODOsAccept user mutation return None;Support ReferenceField of 'self' without raising 'maximum recursion' error.