Having a free hosted MongoDB database is extremely useful for all sorts of projects. mLab offers a great free Sandbox plan with 0.5 GB of storage on a shared instance, this works great for prototyping, or small projects that you are the only user of, and it's easy to scale plans if you need to take your prototype to market.
Creating a new database
Go to mLab and sign up.
Once you are logged in you will be greeted by a control panel like this:
Click the Create new
button to the far right of MongoDB Deployments:
On the next page make sure you click the Single-node
tab under Plan to reveal the free Sandbox
option.
Finally just give your database any name you like and click Create new MongoDB deployment
.
Creating a collection
If you want to be able to insert something to your db you should create a collection
.
You should see a view like this after creating your database, click the + Add collection
button, and just enter any name you want for your collection. I'm going to name mine notes
.
Creating a user
The easiest way to connect to your database from Node.js is to use a mongodb://
URL, you can see that mLab gives us this URL on the database page: mongodb://<dbuser>:<dbpassword>@dsxxxxxx.mlab.com:49207/notetaker
for my database.
The one thing missing there is a user and password for our database, so let's create a user by clicking the Add database user
to the far right of Database Users. Enter whatever username and password you want, make note of them, and copy the mongodb://
URL for your database.
Connecting to your database
You'll need to first npm install mongodb
to get the official MongoClient library.
All we need to do is pass our mongodb://
URL to MongoClient and we'll get back a db connection or an error.
const MongoClient = require('mongodb').MongoClient;
const MONGO_URL = 'YOUR_URL_HERE';
MongoClient.connect(MONGO_URL, (err, db) => {
if (err) {
return console.log(err);
}
// Do something with db here, like inserting a record
db.collection('notes').insertOne(
{
title: 'Hello MongoDB',
text: 'Hopefully this works!'
},
function (err, res) {
if (err) {
db.close();
return console.log(err);
}
// Success
db.close();
}
)
});
There we go, mission accomplished.