Nesting GraphQL With MongoDB

Nesting GraphQL With MongoDB

GraphQL, Apollo server and MongoDB all connected on your app. Let MongoDB how your schemas look like. Let GraphQL how your schemas look like. Let Apollo Server how your going to use these schema

Getting Started

GraphQL, Apollo server and MongoDB all connected on your app.

Dependencies to install

devDependencies are optional, only for the sake of your convenience.

// package.json
{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon --exec babel-node src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
  "apollo-server-express": "^2.19.0",
  "express": "^4.17.1",
  "graphql": "^15.4.0",
  "mongoose": "^5.10.11"
  },
  "devDependencies": {
    "@babel/cli": "^7.12.1",
    "@babel/core": "^7.12.3",
    "@babel/node": "^7.12.1",
    "@babel/preset-env": "^7.12.1",
    "nodemon": "^2.0.6"
  }
}

How it works

There are three things to define to use graphQL and the logic might not be specifically applied to MongoDB + graphQL. The logic is simple.

  1. Let MongoDB how your schemas look like
  2. Let GraphQL how your schemas look like
  3. Let Apollo Server how your going to use these schema

Logic 1. Defining MongoDB Schema

We are making Transaction schema looking like this:

Transaction{
  price
  method
  cardNumber
  paidTime
  items: [
    {
      amount
      quantity  
    }
  ]
}

We are going to use mongoose as ORM for MongoDB. You just need to define its data type and any additional options if any. It is also very simple. You just define each schema and put them together. MongoDB Schema would look like this:

import mongoose from 'mongoose';

const Schema = mongoose.Schema;
const itemSchema = new Schema({
  amount: { type: Number },
  quantity: { type: Number },
});
const transactionSchema = new Schema({
  price: { type: Number, required: true },
  method: { type: String, default: 'VISA', required: true },
  cardNumber: { type: String, required: true },
  paidTime: { type: Date, default: new Date(), required: true },
  items: [itemSchema],
});
export const Transaction = mongoose.model('Transaction', transactionSchema);
  1. Import mongoose
  2. Create a schema instance for item (itemSchema)
  3. Create a schema instance for transaction (transactionSchema)
  4. put itemSchema into items property of transactionSchema object

Notice itemSchema is going to be part of transactionSchema as an array.

Logic 2. Defining TypeDefs

Let’s create a type definition. We are going to use Apollo Server as middleware to handle graphQL. There are other middlewares such as graphql yoga, but Apollo Server is a standard.

Query does things corresponding to GET request, Mutation takes care of any other requests that cause mutation of data such as POST, PUT and DELETE. We are starting by Mutation, because we will push data first, and then fetch them to check if the data properly saved.

There are four type definitions I used in this tutorial:

  • type SchemaName {types} : Defining schema type
  • input nameOfInput {types} : Defining schema’s input, used to type argument’s type
  • type Query {types}: Defining query structure matching to your resolver
  • type Mutation {types}: Defining mutation structure matching to your resolver
// typeDefs.js

import { gql } from 'apollo-server-express';
export const typeDefs = gql`
  scalar Date
// Defining your Query
// 1 Defining your graphql schema type
  type Item {
    id: ID!
    amount: Float
    quantity: Int
  }
  type Transaction {
    id: ID!
    price: Float!
    method: String!
    cardNumber: String!
    paidTime: Date!
    items: [Item]
  }
  // 2 Defining input type
  input ItemInput {
    transactionId: String!
    amount: Float
    quantity: Int
  }

  input TransactionInput {
    price: Float!
    method: String!
    cardNumber: String!
    items: [ItemInput]
  }
  // 3 Defining your Muation
  type Mutation {
    createTransaction(TransactionInput: TransactionInput!): Transaction
    createItem(ItemInput: ItemInput): Transaction

`;

Note: ! mark means this field is required, notice createItem returns Transaction schema

  1. defined Schema of Item and Transaction
  2. defined type of argument which going to be passed into Mutation function
  3. defined two functions to create transaction and to create item.

Logic 3. Defining how you are going to create or update api

Resolver is a function to handle populating your data into your database, you can define how you are going to fetch data and how you are going to update, create data. Since Apollo-server reads from schema from typeDefs, they will need to match how it is structured.

Basic Resolver Structure

const resolver = {

  Query: {
    some async function 
  },
  Mutation: {
    some async function
  }
}

Let’s create resolver file for function and you will need to pass it to apollo server instance. In the Mutation object, add code like so:

Transaction mutation (parent schema)

import { Transaction } from '../models/transaction';

export const transactionResolver = {
  Mutation: {
    createTransaction: async (
      _, { TransactionInput: { price, method, cardNumber } }
    ) => {
      const newtransaction = new Transaction({
        price,
        method,
        cardNumber,
      });
      await transaction.save();
      return newtransaction;
    },
  },
}

Image for post

Firstly, createTransaction is an async function, takes a few arguments but we will only care about the second argument which is what we are going to push to the database and its type.

Secondly, create a Transaction instance imported from mongoose model with input arguments ( price, method, cardNumber) then save the instance using mongoose.

Finally, return the instance.

programming mongodb graphql database nodejs

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

A Simple CRUD App using GraphQL, NodeJS and MongoDB

In my last article, I gave a global introduction to GraphQL. I compared it with REST, as the two of them tend to do the same work, but there are some differences in term of quality and performance. So in this article, we’re going to build a simple movie app, where we can show, add, edit, and delete movies. That way we’ll get through the basics of GraphQL, which is the main goal of this article — as I assume everyone reading this has already worked with NodeJS and MongoDB. A Simple CRUD App Using GraphQL, NodeJS and MongoDB

Seeding a MongoDB Database with NodeJS and Express for the Igbo Dictionary API

I created an ExpressJS endpoint to populate my MongoDB database. This approach was the best for the project since it made the process of creating a newly populated database with just one command. It also made it easier to create temporary databases in testing environments. Seeding a MongoDB Database with NodeJS and Express for the Igbo Dictionary API

Setup a powerful API with Nodejs, GraphQL, MongoDB, Hapi, and Swagger

In this post, you'll see How to Setup a powerful API with Nodejs, GraphQL, MongoDB, Hapi, and Swagger

Building Complex Web App Which Is Data and Assets Heavy with GraphQl, NodeJs and MongoDB (Backend)

We all hear a lot of good things about GraphQl and we all are aware of the benefits which we get using that. In short, we can say GraphQl as the query language for APIs at runtime for fulfilling those queries with the existing data. Its kind of selective querying of data. If we use graphQl combined with the Typescript it provides a better type safety with your graphQl queries, giving us end to end type safety. I will further deep dive into the Type Generation on Front End later in the next blog. I got a chance to get hands on to all these professionally and I would say it has so much of a learning curve that I still get to learn a lot of stuff everyday. Building Complex Web App Which Is Data and Assets Heavy with GraphQl, NodeJs and MongoDb (Backend)

MongoDB Database and java applications

Enroll for free demo to acquire the best knowledge on the schema-less database from live industry experts through MongoDB training