Friday, February 26, 2016

connect to mongoDB from node.js

npm install mongodb --save

add to project folder a new folder data, and create database.js

//database.js
(function (database) {
    var mongodb = require("mongodb");
    var mongoURL = "mongodb://localhost:27017/theBoard";
    var theDB = null;

    database.getDB = function (next) {
        if (!theDB) {
            //connect to the database
            mongodb.MongoClient.connect(mongoURL, function (err, db) {
                if (err) {
                    next(err, null);
                } else {
                    theDB = {
                        db: db
                    }
                    next(null, theDB)
                }
            });
        }
        else {
            next(null, theDB);
        }
    };
})(module.exports);

No comments:

Post a Comment