Building a GraphQL Server with Node.js, Express, and MongoDB - Part 1

Salman Shaikh
3 min readOct 17, 2023

--

GraphQL is a powerful query language for APIs, allowing clients to request exactly the data they need. In this blog, we’ll guide you through the steps to create a GraphQL server using Node.js, Express, and MongoDB. This combination provides a flexible and efficient backend for your applications. We’ll also discuss key files and their roles in the project.

Prerequisites

Before we begin, ensure you have Node.js and MongoDB installed on your system. You can download and install them from their respective official websites.

Step 1: Setting Up the Project

Start by creating a new Node.js project and installing the required dependencies. Here’s how you can do it:

mkdir graphql-mongodb-server
cd graphql-mongodb-server
npm init -y
npm install express express-graphql graphql mongoose cors body-parser

Step 2: Creating the Express Server

In your main application file (let’s call it server.js), you'll create an Express server to run your GraphQL API. It's a good practice to encapsulate server configuration in a class, as demonstrated in the code below:

// Import required packages
import express from "express";
import { graphqlHTTP } from "express-graphql";
import cors from 'cors';
import bodyParser from "body-parser";
import mongoose from "mongoose";

// Import your GraphQL schema (schemaql)

// Create the Express app
class App {
constructor(port) {
this.app = express();
this.port = port;
this.connectToDataBases();
this.initialize();
}

initialize() {
this.app.use(cors({ origin: ['*'] }));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: true }));
this.app.use(
"/graphql",
graphqlHTTP({
schema: schemaql,
graphiql: true,
})
);
}

connectToDataBases() {
const uri = "YOUR_MONGODB_URI";
mongoose.connect(uri);
}

listen() {
this.app.listen(this.port, () => {
console.log("Running a GraphQL API server at http://localhost:4000/graphql");
});
}
}

export default App;

Remember to replace "YOUR_MONGODB_URI" with your actual MongoDB connection string.

Step 3: Creating Your GraphQL Schema

Your GraphQL schema defines the structure of your API. It’s split into two parts: RootQuery and Mutation.


const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields:{
hello: {
type: GraphQLString,
resolve(parent, args) {
return "Hello"
}
}
}
}):

const Mutation = new GraphQLObjectType({
name: "Mutations",
fields:{
hello: {
type: GraphQLString,
resolve(parent, args) {
return "Hello"
}
}
}
});

export default new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
  • RootQuery : This defines the available queries like newsfeed, post, user, and allUser, allowing clients to retrieve data.
  • Mutation: This defines the actions that can change data, such as addUser, addPost, and follow.

Step 4: Running the Server

Create an app.js file and create an instance of your App class and start the server:

import App from "./server";

const port = 4000;
const app = new App(port);

app.listen();

now run the file with the code in the terminal

nodemon app.js

Testing Your GraphQL Server

To test your GraphQL server, you can use tools like Postman or a web browser. Open a browser and navigate to http://localhost:4000/graphql to access the GraphiQL interface, which allows you to interact with your GraphQL API.

It will look like this,

With this setup, you have a fully functional GraphQL server connected to a MongoDB database. You can expand upon this foundation to create more complex queries and mutations to power your application.

We will add queries and mutations in the next part so stay tuned.

--

--