Quick Start: Node.Js, Express, MongoDB

Cole Davis
The Startup
Published in
7 min readJun 30, 2020

Welcome Developers, I am going to explain how to get started with Node.js, Express and MongoDb. I won’t go into depth explaining the code as this guide is meant to get us up and going as quickly as possible.

Getting Started

This guide will assume that you have Node.js installed. In order to check run the following command:

$ node -v
> v13.12.0

With node installed we will create a new project directory

mkdir node-mongo-tut
cd node-mongo-tut

NPM init

Now in our project directory we will run:

npm init

Doing so will prompt us for numerous configuration options, in which we can press “enter” to chose the default value for every option. This process will result in the following package.json file.

{
"name": "mongo-tut",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

NPM modules

With our package.json successfully initialized we can install all of our required dependencies! For this project we will need:

  1. Express.js
  2. body-parser
  3. mongodb

“Express.js, or simply Express, is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js.”

npm install express --save
npm install body-parser --save
npm install mongodb --save

MongoDb Atlas

MongoDB Atlas is the global cloud database service for modern applications. Deploy fully managed MongoDB across AWS, Azure, or GCP. Best-in-class automation and proven practices guarantee availability, scalability, and compliance with the most demanding data security and privacy standards.

Navigate to https://www.mongodb.com/cloud/atlas create an account and upon logging in you will be greeted with:

Choose the leftmost, free option. Next there will be a screen asking you to chose a provider, region, cluster tier, cluster name, and any additional settings.

I will leave everything at default and click “Create Cluster”. Doing so will navigate us to our dashboard where we will be prompted to wait for our cluster to be created. When our cluster is created we will see a screen like:

Our next step is to click the button labeled “connect”, on click we will see:

Click “Add Your Current IP Address” and your IP address will automatically be populated in the text box, then click “Add IP Address”. Next chose a username and password for the admin user of our database and click “Create MongoDB User” Next click “Choose a Connection” where you will be prompted by this screen:

Chose “Connect your application” and you will see:

Copy the connection string and return to your code editor to finish the connection.

Connecting

Create a new file server.js in our project directory.

touch server.js

In server.js paste the following code, be sure to replace the “password” variable with the password you chose for the user in MongoDb Atlas and <dbname> with an arbitrary database name of your choosing.

// server.js
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
app.use(bodyParser());const password = "L95ddjbTxcZgGpho";
const connectionString = `mongodb+srv://user:${@cluster0-dh8wy.mongodb.net">password}@cluster0-dh8wy.mongodb.net/ColesDb?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, {useUnifiedTopology: true})
.then(client => {
console.log("Connected to Database");
})

If everything is correct, you should see “Connected to Database” logged upon running “node server.js”.

node server.js
> Connected to Database

Adding data to our database (CREATE)

At this point our database is configured for full CRUD capability. Let’s first start by serving our user a form in which they can send data to our database.

touch index.html

In index.html we have a bare bones form element that takes a dog name as input, and on submit sends the form data to the endpoint “dog-names”.

<!-- index.html -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My app</title>
</head>
<body>
<h1>Mongo Form</h1>
<form action="/dog-names" method="POST">
<input type="text" placeholder="dog name" name="dogName" />
<button type="submit">Submit</button>
</form>
</body>
</html>

In order for our user to see the form we will need to serve it in our back-end. We can simply add the following code to our server.js file:

// server.js...MongoClient.connect(connectionString, {useUnifiedTopology: true})
.then(client => {
... app.get('/form', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.listen(3000, () => {
console.log("listening on 3000")
})
... })

Now with our server running (node server.js) we can see our form!

Now to handle the route for our POST request to “dog-names”. In server.js, still within our MongoClient .then callback, we add the following code:

// server.js...const db = client.db("pet-store")
const dogNameCollection = db.collection("dog-names")
app.post("/dog-names", (req, res) => {
dogNameCollection.insertOne(req.body)
.then(result => {
res.redirect('/form')
})
.then(console.error)
})
...

After adding the aforementioned code to your server.js file, restart your server and send your favorite dog name through your form. Then navigate back to your cluster dashboard on MongoDB atlas. Click “collections” and you should see your new entry:

READ

Now let’s try reading some of the dog names we stored in our database. Once again in server.js, inside our MongoClient .then callback argument, we will write a route to handle our GET request.

// server.js...    app.get('/dog-names', (req, res) => {
db.collection('dog-names').find().toArray()
.then(results => {
res.send(results)
})
.catch(console.error)
})
...

Restarting our server and visiting our ‘/dog-names’ route we will see:

UPDATE

Next up: Updating. Let’s add another route in the same place inside of our callback in server.js.

// server.js...    app.put('/dog-names', (req, res) => {
dogNameCollection.findOneAndUpdate(
{dogName: req.body.dogName},
{
$set: {dogName: req.body.newName}
}
)
.then(console.log)
.catch(console.error)
res.redirect('/dog-names');
})
...

Instead of creating another HTML file to send our update request I will be using Postman.

After hitting send we can check our GET route to see if our updates have persisted. If it worked we should see the dogName “Riley”, replaced for “Snoopy”.

DELETE

The time has come to delete our precious dogs. Let’s add one final piece of code to our server.js inside of our .then callback.

// server.js...    app.delete('/dog-names', (req, res) => {
dogNameCollection.remove(
{dogName: req.body.dogName},
)
.then(console.log)
.catch(console.error)
res.redirect('/dog-names')
})
...

Currently our list of dogs is:

Let’s try to delete “Plato” from our cluster. In Postman we can send our DELETE request.

After pressing send we refresh our cluster and see that “Plato” is no more.

Server.js

// server.js
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
app.use(bodyParser());const password = "L95ddjbTxcZgGpho";
const connectionString = `mongodb+srv://user:${@cluster0-dh8wy.mongodb.net">password}@cluster0-dh8wy.mongodb.net/ColesDb?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, {useUnifiedTopology: true})
.then(client => {
console.log("Connected to Database")
const db = client.db('pet-store')
const dogNameCollection = db.collection('dog-names')
app.get('/form', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.get('/dog-names', (req, res) => {
db.collection('dog-names').find().toArray()
.then(results => {
res.send(results)
})
.catch(console.error)
})

app.put('/dog-names', (req, res) => {
dogNameCollection.findOneAndUpdate(
{dogName: req.body.dogName},
{
$set: {dogName: req.body.newName}
}
)
.then(console.log)
.catch(console.error)
res.redirect('/dog-names');
})
app.post('/dog-names', (req, res) => {
dogNameCollection.insertOne(req.body)
.then(result => {
res.redirect('/form')
})
.then(console.error)
})
app.delete('/dog-names', (req, res) => {
dogNameCollection.remove(
{dogName: req.body.dogName},
)
.then(console.log)
.catch(console.error)
res.redirect('/dog-names')
})
app.listen(3000, () => {
console.log('listening on 3000')
})
})

Conclusion

I wrote this guide with the intention to get developers up and running with as little reading as possible. The idea is to supplement this setup guide with the documentation and off you go!

Resources:

https://zellwk.com/blog/crud-express-mongodb/

--

--