Connect to the MongoDB Database
Learn how to implement a GraphQL application with MongoDB Database.
We'll cover the following
Introduction
The storage used so far isn’t persistent, and the authentication feature hasn’t been available. Let’s replace it with persistent storage using the MongoDB database and add the authentication feature using the JSON Web Token (JWT) mechanism.
Define a configuration
Note: The
.env
file is required if a local machine is used. However, it has already been set up for you on the Educative platform.
We start by defining the database configuration, including the database name and the MongoDB URI, inside the .env file. Make sure to define the MongoDB URI based on the type of MongoDB used.
Note: If MongoDB is used locally (or via Docker), the MongoDB URI is
mongodb://localhost:27017
.If MongoDB Atlas is used, the MongoDB URI is
mongodb+srv://...
(the complete MongoDB URI can be seen in the MongoDB Atlas dashboard page).
DATABASE_NAME=gqlblog
MONGO_URI=mongodb://localhost:27017
Inside the .env
file, we define the configuration for the JWT, including the JWT secret key and JWT secret key expiration time.
JWT_SECRET_KEY=mysecretkey
JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT=15
Create a connection to the database
Before creating a connection to the database, we create a helper function to get the value from the .env
file. We create the helper in the utils.go
file inside the utils
directory. This directory is located in the same location in the server.go
file.
Get hands-on with 1400+ tech skills courses.