Q: MongoDB Connect to database I am doing an app in node.js and I found this syntax for connecting mongodb. I know there are other ways but can someone please explain to me this one. What is connecting here? How does this callback argument in function works? What is assert used for?
var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');

var url = 'mongodb://localhost:27017/myproject';

var mongoClient = new function () {

    this.connect= function(callback) {
        MongoClient.connect(url, function (err, db) {
            console.log("Connected successfully to server");
            callback(err, db);
        });
    }
}

module.exports = mongoClient;


A: 
What is connecting here?

You run a MongoDB server instance before you run this code. The server runs on a port(generally port 27017). The thing you are trying to connect is that server instance via your node.js program. 

How does this callback argument in function work?

MongoClient.connect(url, function(err,db){});
This function tries to connect to a MongoDB server at port 27017 to database myproject. It stores the result of connection in two arguments of that function. Stores null in error argument if you have a successful connection otherwise, stores the stack trace of error. In the case of successful connection, its sends you a DB instance in the second argument.
The callback function returns the same result to the calling function.

What is assert used for?

It's a module in Node. What it is used for is given here in the beautiful Node.JS documentation about it

A: var MongoClient = require('mongodb').MongoClient,

In this line you are requiring the mongodb library.
var url = 'mongodb://localhost:27017/myproject';

This is the url  where you connect. The format is mongodb://host_address:port/db_name
//Creating a function with the name mongoClient and exporting it.
var mongoClient = new function () {
  //Creating another called connect inside the mongoClient function. Which you will call from other place to connect to the db. 
  this.connect= function(callback) {
    //Here the mongo client library actually connecting to mongo server, and through the callback function it return err and db object. if the connection is successful only then you should return db.
    MongoClient.connect(url, function (err, db) {
        if(!err){
           console.log("Connected successfully to server");
           //Here the call back function of the function which call the connect function getting called.
           callback(err, db);
        }else{
          throw (err);
        }
    });
  }
}
//here you are exporting the mongoClient function.
module.exports = mongoClient;

From other file you connect to mongo like this.
var mongoClient = require('relative path to this file');
mongoClient.connect(function(err, db){
  //now db is the connection object.
  console.log(db);
});

