Search code examples
mongodbgraphqlmongoenginegraphene-python

make ID field required with MongoEngineObjectType


I use graphene with graphene-mongo. My graphql schema has a type similar to this:

type Report {
   id:ID!
   name:String!
}

My graphene class for this type is

class Product(MongoengineObjectType):

    class Meta:
        model = MongoProduct

and the mongoengine class is

class MongoProduct(mng.DynamicDocument):        
    name = mng.fields.StringField(required=True)

How can I make the field id required? GraphiQL shows an exclamation mark next to name, but not next to id.


Solution

  • class MongoProduct(mng.DynamicDocument):
        id = ObjectIdField(primary_key=True, required=True)    # Optional: Add default=bson.ObjectId        
        name = mng.fields.StringField(required=True)
    

    id can also be a IntField or a StringField but I'd recommend to stick to an ObjectId