Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using GraphQL with MongoDB

Introduction

GraphQL is a query language for your API, and a runtime for executing those queries by using a type system you define for your data. This tutorial will guide you through the steps to set up a GraphQL server with MongoDB as the data source, using Node.js and Apollo Server.

Setting Up

To get started, you need to set up a Node.js project and install the necessary dependencies:

Setting Up the Project

mkdir graphql-mongodb
cd graphql-mongodb
npm init -y
npm install apollo-server graphql mongoose
            

Connecting to MongoDB

Create a db.js file to handle the connection to MongoDB:

db.js

const mongoose = require('mongoose');

const connectDB = async () => {
    await mongoose.connect('mongodb://localhost:27017/graphql', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    console.log('MongoDB connected');
};

module.exports = connectDB;
            

Defining GraphQL Schema

Create a schema.js file to define your GraphQL schema and resolvers:

schema.js

const { gql } = require('apollo-server');

const typeDefs = gql`
    type User {
        id: ID!
        name: String!
        email: String!
    }

    type Query {
        users: [User]
        user(id: ID!): User
    }

    type Mutation {
        addUser(name: String!, email: String!): User
    }
`;

const User = require('./models/User');

const resolvers = {
    Query: {
        users: () => User.find(),
        user: (_, { id }) => User.findById(id),
    },
    Mutation: {
        addUser: (_, { name, email }) => {
            const user = new User({ name, email });
            return user.save();
        },
    },
};

module.exports = { typeDefs, resolvers };
            

Creating the User Model

Create a models/User.js file to define the MongoDB schema and model:

User.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
});

module.exports = mongoose.model('User', userSchema);
            

Setting Up Apollo Server

Create an index.js file to set up Apollo Server and connect everything together:

index.js

const { ApolloServer } = require('apollo-server');
const connectDB = require('./db');
const { typeDefs, resolvers } = require('./schema');

connectDB();

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
    console.log(`🚀 Server ready at ${url}`);
});
            

Running the Server

Start the server by running the following command:

Starting the Server

node index.js

You should see the message "Server ready at http://localhost:4000" indicating that the GraphQL server is running.

Testing the GraphQL API

Open your browser and navigate to http://localhost:4000 to access the GraphQL Playground. Here you can run queries and mutations to test your GraphQL API.

Example Query

query {
    users {
        id
        name
        email
    }
}
            

Example Mutation

mutation {
    addUser(name: "John Doe", email: "john.doe@example.com") {
        id
        name
        email
    }
}
            

Conclusion

In this tutorial, you have learned how to set up a GraphQL server with MongoDB as the data source using Node.js and Apollo Server. This setup allows you to create a flexible and powerful API for interacting with your MongoDB data.