Video tutorial: how to easily connect MongoDB with Node.js

Hi guys! In this tutorial I will explain to you how you can easily connect a MongoDB database with Node.js. Also, I will explain how to insert a document into MongoDB database by using Node.js.

First of all, go to mongolab.com and create an account. Then you must create a database with an user.

Next,  create a js file on your computer, open command line and enter this command: npm install mongodb

In the created js file, add this code:
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("You must use here the URI from MongoLab", function(err, db) {
if(!err) {
console.log("We are connected");
}
});

Now, open command line and enter: node yourjsfile

You will see We are connected

To insert a new document in your database, you can use this code:

MongoClient.connect("You must use here the URI from MongoLab", function(err, db) {
if(err) { return console.dir(err); }

var collection = db.collection('demodb');
var doc1 = {'hello':'Hello World!'};

collection.insert(doc1);

});

Video tutorial:









Leave a Comment