Subscribe
How to Use GraphQL with Node.js and MongoDB
6 mins read

By: vishwesh

How to Use GraphQL with Node.js and MongoDB

GraphQL is a query language that enables developers to request specific data from APIs in a more efficient and flexible way than traditional REST APIs. Node.js is a popular server-side JavaScript runtime, and MongoDB is a NoSQL database that stores data in JSON-like documents. In this tutorial, we will walk through how to use GraphQL with Node.js and MongoDB to build a powerful and scalable backend for your web or mobile applications.

Prerequisites

Before we dive into the tutorial, you should have some basic knowledge of Node.js, MongoDB, and GraphQL. You should also have Node.js and MongoDB installed on your computer.

Step 1: Set up a new Node.js project

First, we need to create a new Node.js project. Open up your terminal and create a new directory for the project.

mkdir graphql-node-mongodb
cd graphql-node-mongodb

Next, initialize a new Node.js project using npm.

npm init -y

This will create a package.json file in your project directory.

Step 2: Install the required dependencies

We will need to install the following dependencies for our project:

  • express: A popular Node.js web framework.
  • graphql: The GraphQL library.
  • express-graphql: A library that provides a simple way to create a GraphQL HTTP server with Express.
  • mongoose: A MongoDB object modeling library.

Install the dependencies by running the following command:

npm install express graphql express-graphql mongoose

Step 3: Set up a MongoDB database

Now we need to set up a MongoDB database to store our data. You can either install MongoDB locally or use a cloud-based MongoDB service like MongoDB Atlas.

Once you have set up your MongoDB database, create a new database and collection for your project.

Step 4: Define your GraphQL schema

In GraphQL, the schema is the contract between the server and the client. It defines the types of data that can be queried and the relationships between them. Let's create a schema.js file in the root of our project and define our schema.

const { GraphQLObjectType, GraphQLString, GraphQLSchema } = require('graphql');

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    email: { type: GraphQLString },
  },
});

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: UserType,
      args: { id: { type: GraphQLString } },
      resolve(parent, args) {
        // Resolve logic goes here
      },
    },
  },
});

const schema = new GraphQLSchema({
  query: QueryType,
});

module.exports = schema;

In this schema, we define a User type with three fields: id, name, and email. We also define a Query type with a single field user, which takes an id argument and returns a User object.

Step 5: Connect to the MongoDB database

Now we need to connect our Node.js server to the MongoDB database. Create a new file called db.js in the root of your project and add the following code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/graphql-node-mongodb', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  console.log('Connected to MongoDB');
});

In this file, we use the mongoose library to connect to our MongoDB database. We specify the connection string as mongodb://localhost:27017/graphql-node-mongodb, where graphql-node-mongodb is the name of our database.

Step 6: Implement the resolver functions

Resolver functions are responsible for retrieving the data from the data source. In our case, we will be retrieving data from the MongoDB database. Let's create a new file called resolvers.js in the root of our project and implement the resolver functions.

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

const resolvers = {
  Query: {
    async user(parent, args) {
      return await User.findById(args.id);
    },
  },
};

module.exports = resolvers;

In this file, we define a resolver function for the user field of the Query type. This function takes an id argument and returns a User object with the corresponding id from the MongoDB database.

We also need to define a User model for our MongoDB database. Create a new file called models/User.js and add the following code:

const mongoose = require('mongoose');

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

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

In this file, we define a User schema with two fields: name and email. We also export a User model based on this schema.

Step 7: Create the GraphQL server

Now we can create our GraphQL server using Express and express-graphql. Create a new file called server.js in the root of your project and add the following code:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema');
const resolvers = require('./resolvers');
const db = require('./db');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: resolvers,
  graphiql: true,
}));

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In this file, we create a new Express app and mount the graphqlHTTP middleware to the /graphql endpoint. We pass in our GraphQL schema and resolver functions, as well as the graphiql option, which enables the GraphiQL IDE for testing our queries.

Step 8: Test your GraphQL API

Now that our server is up and running, let's test our GraphQL API using the GraphiQL IDE. Open up your web browser and navigate to http://localhost:3000/graphql.

You should see the GraphiQL IDE, which allows you to write and execute GraphQL queries. Let's try running the following query to retrieve a user with a specific id:

query {
  user(id: "123") {
    id
    name
    email
  }
}

Make sure to replace 123 with a valid id from your MongoDB database. You should see a JSON response with the id, name, and email of the user.

Conclusion

In this tutorial, we learned how to use GraphQL with Node.js and MongoDB to build a powerful and scalable backend for our web or mobile applications. We covered how to set up a new Node.js project, install the required dependencies, connect to a MongoDB database, define our GraphQL schema, implement the resolver functions, and create a GraphQL server using Express and express-graphql. We also tested our GraphQL API using the GraphiQL IDE. With this knowledge, you can go on to build more complex GraphQL APIs that meet the specific requirements of your application. GraphQL provides a flexible and efficient way to query and manipulate data, and when combined with Node.js and MongoDB, it offers a powerful and scalable solution for building modern web and mobile applications.

Further Reading

If you're interested in learning more about GraphQL, Node.js, and MongoDB, here are some resources to get you started:

By following these resources, you can gain a deeper understanding of GraphQL, Node.js, and MongoDB, and become proficient in building powerful and scalable applications. Good luck!

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories