Reading from MongoDB database in Javascript with MongoClient

László Harri Németh
The Coding Hype
Published in
4 min readJan 2, 2019

--

This is a short tutorial and an example app which reads data from a MongoDB database. The app is using MongoDB, Express.js and Node.js. I’m using Apple macOS High Sierra 10.13.4 (17E199), Node.js v9.10.1, npm 5.6.0.

“MacBook Pro showing vegetable dish” by Igor Miske on Unsplash

Keywords: Node.js, NPM, Javascript, MongoDB, MongoClient, Express.js, macOS

DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.

Required knowledge

In this article I will use the following technologies:

  • Linux
  • Javascript
  • Node.js
  • Express.js
  • MongoDB
  • MongoClient

Table of Contents

This article has the following sections:

  • MongoDB installation
  • Data preparation
  • Express app creation
  • Express server implementation: without db read
  • Express server implementation: implementing db read using MongoDB Node.js driver
  • Closing words

MongoDB installation

MongoDB is a free and open-source cross-platform document-oriented NoSQL database program, which uses JSON-like documents with schemas. Express.js is a minimalist web application framework or Node.js. Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side. (Source: Wikipedia)

First we need to install MongoDB. In this article I will install it by downloading community server from mongodb.com. Let’s extract the tgz file. I will use ~/mongodb to store the mongodb runtime.

cd ~
tar -zxvf mongodb-osx-ssl-x86_64-3.6.3.tgz
mv mongodb-osx-ssl-x86_64-3.6.3 mongodb

MongoDB (mongod) defaults the database location to /data/db/.

Let’s create this directory, and change its owner (id -un gets the username):

sudo mkdir -p /data/db
sudo chown -R `id -un` /data/db

Now we can start the MongoDB server (mongod):

cd ~
./mongodb/bin/mongod

Data preparation

In this step we prepare the test data in our MongoDB database, so that we can use it in our app.

“photo of 5-story library building” by Tobias Fischer on Unsplash

In a different shell window we need to start the MongoDB shell (mongo).

./mongodb/bin/mongo

In the MongoDB shell we can issue commands to the mongodb server to manipulate data in the database.

MongoDB stores data records in collections and the collections in databases. In this step we will create a new database called tododb. For this we will use the use statement.

use tododb

(The shell will return switched to db tododb.)

We will create a new collection todolist in this tododb database, and a new document in this todolist collection. The following command will create the collection as well as the new document.

db.todolist.insertOne({description: 'Register for the marathon', details: 'it must be done until 4.7.2018'})

The shell returns something like the following:

{
"acknowledged" : true,
"insertedId" : ObjectId("5ac8fbc723f00907d3d1be99")
}

This means the document was created successfully. You can query this by the following command:

db.todolist.find()

Result:

{ "_id" : ObjectId("5ac8fbc723f00907d3d1be99"), "description" : "Register for the marathon", "details" : "it must be done until 4.7.2018" }

Or in a formatted way:

db.todolist.find().pretty()

Result:

{
"_id" : ObjectId("5ac8fbc723f00907d3d1be99"),
"description" : "Register for the marathon",
"details" : "it must be done until 4.7.2018"
}

Let’s add another entry to the todolist:

db.todolist.insertOne({description: 'Get money from ATM', details: '100 USD'})

Express app creation

In this step we will create an express app. For this we need a new directory. We initialize the content (actually the package.jsonfile) with npm.

npm init -y

We need to install Express by issuing the following command. --save will save the dependency to package.json. We will also install mongodb which is the official MongoDB driver for Node.js.

npm install --save express mongodb

Express server implementation: without db read

Create index.js:

touch index.js

The implementation of the server looks like the following. This needs to be put to index.js

var express = require('express');
var app = express();
app.get('/', (req, res) => {res.send('Hello World!')})
app.listen(3000, () => console.log('Example app listening on port 3000!'))

The app can be run by issuing the following command:

node index.js

And then in the web browser enter localhost:3000 to the URL.

Express server implementation: implementing db read using MongoDB Node.js driver

To read the data from the database the MongoDB Node.js driver MongoClient is used.

“closeup photo of eyeglasses” by Kevin Ku on Unsplash

For this we need to enhance index.js. The final code looks like the following. Please see the comments.

The app can be started using

node index.js

Closing words

Thank you for reading this article. You can find the final implementation in my Github page:

--

--

László Harri Németh
The Coding Hype

Software developer. Python, SQL, ABAP, Swift, Javascript, Java, C, C++, Ruby, noSQL, Bash, Linux. http://nlharri.hu http://github.nlharri.hu hello@nlharri.hu