How to set up a MongoDB environment along with npm

3 min read ⋅ 760 views

The Node Package Manager (npm) is basically a magic wand for programmers. It lets you download and install from a huge library of useful and functional packages. As it is, it also helps you set up many types of environments, including the most famous NoSQL JSON based database yet, MongoDB. 

Among the advantages NoSQL offers over Relational databases, there's the ability to scale horizontally. This means we can partition our database into many servers, effectively balancing the load on the whole database. This process is called sharding.

It's also perfect for handling large volumes of rapidly changing structured, semi-structured, and unstructured data.

To start off, you’ll have to get npm and MongoDB downloaded and installed on your machine. 

To those of you who haven't heard of npm, it is basically the package manager for Node. As for MongoDB, we are using the Community Server, which is ideal for testing setups like this. You also have MongoDB Atlas, a cloud-based solution offering many advantages, as well as the Enterprise Server. Feel free to check them out should you be interested.

Once you download the npm folder, you'll have to extract it to the directory of your choice, in this case, I'm using /usr/local/lib. Enter the following command replacing with the correct path your file has been downloaded in:

mv /home/myuser/Downloads/node-v8.11.2-linux-x64.tar.xz /usr/local/lib
cd /usr/local/lib && tar xz node-v8.11.2-linux-x64.tar.xz  

Now, you can edit the file ~/.profile and add the following lines and save it:

export NODEJS_HOME=/usr/local/lib/node-v8.11.2-linux-x64/bin

Once that's done, enter:

source ~/.profile

What source does is executing the commands in the file, so they will be added to our PATH environment variable.

As good as npm can be, we still need to manually start the database server so it can listen to our requests. 

A humongous DB

Once we've downloaded the compressed file for MongoDB, we'll have to extract the contents to a directory of our choice and copy the binary folder URL into our environment variables in order to be able to use all the commands we need. We can use the same syntax as before, editing the ~/.profile file:

export MONGO_HOME=/usr/local/lib/mongodb-linux-x86_64-debian81-3.6.4/bin

Now we're going to start the Community Server on the default port 27017, enter the following command into your consoles:


Before we can connect to the database, if you're using Linux, we'll need one more package that can be downloaded via APT:

apt install mongodb-clients

Then, we can finally execute:


Which will log us into the server, the MongoDB shell.

MongoDB ships with an already existing database called test. You can verify this by typing the following:


Next, we want to use the command:


In which collectionName refers to any name you could have in mind and the function insert() takes in a JSON as a parameter. You can put anything you want inside of this JSON, but it is recommended you keep an ordered and semi-relational structure when doing so.

The name of the function is pretty self-explanatory. We can check what we've just inserted with the command:


Which, if you haven't passed any JSON as a parameter, will return all the documents, that is, all the 'rows' of the collection. The MongoDB shell is also a Javascript interpreter, so things like this are perfectly allowed:

var a = db.collectionName

You'd do yourself a favor to check out the documentation for MongoDB CRUD (Create, Read, Update, Delete).

The Node side of things

We now want to head back to our consoles and create a test folder called, for all intents and purposes, mongodbtest

cd ~ && mkdir mongodbtest && cd mongodbtest/

Once there, input the command:

npm init 

This will create a package.json file where information about the packages you've installed is stored. Now we're ready to install the main package that'll do the magic here, mongodb. Do this by typing:

npm install --save mongodb

The --save flag is used to fixate the package name into the package.json file, that is, your dependencies.

Finally, we dust off our text editors and write the following script:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017';
MongoClient.connect(url, { useNewUrlParser:true } , function(error,database){
console.log('Connected successfully');
const testdb = database.db('test');

Save it under script.js and in the console, execute:

node script.js

As you can see, the connect() function receives three parameters: the URL, an options object and a callback function which will either return an error, if failed, or an object representing the database, if successful. We can insert this asynchronous function wherever we may like, for example, in functions listening to RESTful methods like GET, POST, PUT, PATCH, DELETE and so on.

If the operation was successful, after you restart your MongoDB shell, you should effectively see a new users collection and the new data that has been inserted.

You'll want to follow along the CRUD documentation for MongoDB to gain access to the whole range of operations you can execute from a remote (or local) Node server.

I hope you found this useful.


Deploying React and Node to Heroku

React is a frontend library built with Javascript that executes in the client's browser. When programming with React we ...