Connect MongoDB database to Express server — step-by-step

Sharmila S
May 2 · 4 min read

In this article, I am going to give an explanation of the steps for getting started with MongoDB for express backend.

For accessing MongoDB database from express, we use Mongoose which is an Object Data Modelling library providing all necessary functions to access and work with MongoDB.

npm modules used:

  • express — for our backend server.
  • mongoose — for working with MongoDB
  • dotenv —for providing credentials using environment variables

First, let’s make our work directory ready.

$ mkdir express-mongodb
$ cd express-mongodb

Step 1: Initialise npm on the directory and install the necessary modules. Also, create the index file. (To get started with express, read this article )

$ npm init
$ touch index.js
$ npm i express mongoose

Step 2: Initialise the express app and make it listen to a port on localhost.

const express = require("express");const app = express();app.listen(3000, () => console.log("Server is running"));

Step 3: Require mongoose package

const mongoose = require("mongoose");

Connect to a cluster in MongoDB cloud

1. Connection code

Provide the MongoDB URI of your cluster to mongoose.connect() ( refer to this article for creating a free-tier cluster for MongoDB in the cloud)

mongoose.connect(
process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);

process.env.MONGODB_URI — used to get value from environment variable

It is recommended to use an environment variable so that your credentials will not be exposed when you are uploading your repository online.

dotnev npm package can be used to provide environment variables

$ npm i dotenv
  • In the index.js file, add the following at the top.
require("dotenv").config(); 
  • Create a .env file and provide your credentials there in the provided format (key=value)
MONGODB_URL="your-mongodb-uri-here"

Make sure you included .env file along with node_modules directory in .gitignore.

.gitignore file

2. Define a schema

Let’s create a schema for a new collection.

Schema defines the structure of the document, with all the field names and type.

const studentSchema = new mongoose.Schema({
roll_no: Number,
name: String,
year: Number,
subjects: [String]
});

mongoose.schema() takes in a javascript object.

Name of the property is the fields for the document
Value for the property represents the type for the particular field.

To make any field required, make required as true.

roll_no: {
type: Number,
required: true
}

Since we wanted to specify that it is required i.e. to send another information along with the type of the field, we represent the values that are to be sent in an object.

To know more about the schema types, read the documentation here.

3. Define the model

Let’s create our model by passing in the schema and a name for our model.

const Student = mongoose.model('Student', studentSchema);

- studentSchema — the schema we have created just now
- ‘Student’ — Name for the model, so a collection will be created with a name ‘students’ (plural form of the name with all lowercase)

Now as our model is ready, we can create APIs to get, add, delete, update our documents within our collection.

Let’s add two documents whenever our app is loaded

const stud = new Student({
roll_no: 1001,
name: 'Madison Hyde',
year: 3,
subjects: ['DBMS', 'OS', 'Graph Theory', 'Internet Programming']
});
stud.save().then(() => console.log("One entry added"));

By sending an object containing the values to our model Student, we can create a new document and use save() method to save our document to the cloud.

Now, Let's define a get request for the root route which returns all the documents in Student collection which should return the document we added.

app.get('/', (req, res) => {
Student.find({}, (found, err) => {
if (!err) {
res.send(found);
}
console.log(err);
res.send("Some error occured!")
})
});

model.find() finds and returns documents

The first parameter {} — to specify queries to receive documents that match a certain condition. (Here, we leave it blank to get all the documents)

The second parameter is a callback function, which returns documents found and error if any occurs.

res.send(found) returns the documents found back as a response

Let’s try running our app!

console

You can see ‘MongoDB connected’ and ‘One entry added’ messages in our console.

Request the root route ‘/’ from the browser to receive the response.

It works!! You have connected MongoDB with express. Now it’s your turn to try out different MongoDB queries and types.

Github repo link —SharmilaS22/medium-express-mongodb

Happy Learning!

featurepreneur

Features for everyone!