DEV Community

Discussion on: Mongodb + GraphQL + Django

Collapse
 
hyperredstart profile image
HyperRedStart

Hi,

Step 1.

You need to create model for your collection .

from django.db import models
from mongoengine import Document
from mongoengine.fields import (
    FloatField,
    StringField,
    ListField,
    URLField,
    ObjectIdField,
)

# Create your models here.
class Shoes(Document):
    meta = {'collection' : 'shoes'}
    ID = ObjectIdField()
    name = StringField()
    brand = StringField()
    model = StringField()
    price = FloatField()
    img = URLField()
    color = ListField(StringField())
Enter fullscreen mode Exit fullscreen mode

Step 2.

Using graphene is a GraphQL API library for Python create a type for your collection.

import graphene
from graphene import relay
from graphene_mongo import MongoengineObjectType
from .models import Shoes

class Connection(graphene.Connection):
    class Meta:
        abstract = True

    total_count = graphene.Int()

    def resolve_total_count(self, info):
        return self.iterable.count()

class ShoesType(MongoengineObjectType):
    class Meta:
        model = Shoes
        interfaces = (relay.Node,)
        connection_class = Connection
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith']
        }
Enter fullscreen mode Exit fullscreen mode

Step 3.

Delcare your type for graphene schema.

import graphene
from graphene.relay import Node
from graphene_mongo.fields import MongoengineConnectionField
from shoes.models import Shoes
from store.models import Store
from shoes.types import ShoesType
from store.types import StoreType

class Mutations(graphene.ObjectType):
    pass

class Query(graphene.ObjectType):
    # node = Node.Field()
    stores = MongoengineConnectionField(StoreType)
    shoes = MongoengineConnectionField(ShoesType)
    shoes_list = graphene.List(ShoesType)

    def resolve_shoes_list(self, info):
        return Shoes.objects.all()


schema = graphene.Schema(query=Query, types=[StoreType, ShoesType])
Enter fullscreen mode Exit fullscreen mode

That's the roughly process of using graphql with mongodb thank you!

Collapse
 
shlokabhalgat profile image
shlokabhalgat

Thanks @hyperredstart ! I just had one more question-
Will Step 2 code be in schema.py or models.py?

Thread Thread
 
hyperredstart profile image
HyperRedStart

Hi @shlokabhalgat
Step 2 is separate from schema.py, As you wish you could place TypeObject code in the schema.py.

Thanks!

Thread Thread
 
shlokabhalgat profile image
shlokabhalgat

Thanks a lot @hyperredstart I was able to do it! Keep up the good work😁