Mongodb + GraphQL + Django
Tags: document, mongodb, graphql, django
Published: 2022-03-01 06:27:43

---
title: Mongodb + GraphQL + Django
tags: Document, mongodb, graphql, django
author: Corey Lai
---

# Mongodb + GraphQL + Django
## Mongodb installation
[Mongodb Image](https://hub.docker.com/_/mongo)
![](https://i.imgur.com/3o6yGw1.png)

```bash=
docker pull mongo
docker run --name mongodb mongo
docker ps
================================
CONTAINER ID        IMAGE               COMMAND                  CREATED      STATUS              PORTS                      NAMES
2fef936de7f9        mongo               "docker-entrypoint.s"    10 days ago  Up About an hour    0.0.0.0:27017->27017/tcp   mongodb
```

## Mongodb Compass
[Mongodb Compass](https://www.mongodb.com/try/download/compass)
![](https://i.imgur.com/uMxBsa4.png)
![](https://i.imgur.com/8XCnA1d.png)
![](https://i.imgur.com/FtAYoao.png)


## Django Constructor
```bash=
conda update conda
conda create --name NGDP python=3.6
activate NGDP
(NGDP) D:\NGDP>

conda install -y Django=3.1.2
conda install -y -c conda-forge django-cors-headers
conda install -y  -c conda-forge graphene-django
conda install -y  -c conda-forge graphene-mongo
conda install -y  -c conda-forge django-filter
conda install -y  -c conda-forge mongoengine
conda install -y  -c conda-forge mongomock
conda install -c conda-forge neo4jdjango
conda install pytest
conda install pytest-django

django-admin startproject ngdp
conda install pip
```
## Start Project
```bash=
django-admin startproject shoesstore
cd shoesstore
django-admin startapp store
django-admin startapp shoes
```
## Start Programming (Backend)
### Project Structure
![](https://i.imgur.com/u5QD3GS.png)

shoesstore/settings.py
```python
# 載入 mongodb 引擎
from mongoengine import connect

# 允許所有裝置連線
ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 預載程式
    'graphene_django',
    'graphene_mongo',
    'store',
    'shoes'
]

# mongodb connection
_MONGODB_USER = ""
_MONGODB_PASSWD = ""
_MONGODB_HOST = "localhost"
_MONGODB_NAME = "shoesstore"
_MONGODB_PORT = 27017
_MONGODB_DATABASE_HOST = "mongodb://%s:%s@%s/%s" % (
    _MONGODB_USER,
    _MONGODB_PASSWD,
    _MONGODB_HOST,
    _MONGODB_NAME,
)

connect(_MONGODB_NAME, host=_MONGODB_HOST, port=_MONGODB_PORT)

# Graphql Schema
GRAPHENE = {"SCHEMA": "shoesstore.schema.schema"} 
```

shoesstore/urls.py
```python
# 增加 graphql 路徑，csrf_exempt 跨網站請求豁免
urlpatterns = [
    path('admin/', admin.site.urls),
    path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True)), name="graphql-query")
]
```
### Graphql
```graphql=
query ($name: String) {
  bikes(first:1, name_Istartswith: $name) {
    totalCount
    pageInfo {
      hasPreviousPage
      hasNextPage
    }
    edges {
      node {
        name
        brand
        year
        size
        wheelSize
        type
      }
    }
  }
}
```

```graphql=
query {
  allCategories(first: 1, after: "opaqueCursor") {
    edges {
      node {
        name,
        ingredients {
          edges {
            node {
              name
            }
          }
        }
      }
    }
      pageInfo {
        hasNextPage
      }
  }
}
```

```graphql=
{
  shoes(first: 2) {
    totalCount
    pageInfo {
      startCursor
      hasNextPage
      hasPreviousPage
      endCursor
    }
    edges {
      cursor
      node {
        name
        brand
        model
        id
      }
    }
  }
}
```

```
query ($name: String) {
  bikes(first:2, name_Istartswith: $name, after: "YXJyYXljb25uZWN0aW9uOjE=") {
    totalCount
    pageInfo {
      endCursor
      hasPreviousPage
      hasNextPage
    }
    edges {
      node {
        id
        name
        brand
        year
        size
        wheelSize
        type
      }
      cursor
    }
  }
}

```

### React Native App
```bash=
expo init ShoesStoreProjectR
```