How to define mongoDB database connection variable globally - node.js

I have worked to node js + mysql. but now i am going to node js + mongoDB
I am in need to connect database and make a variable for globally use.
I am very much confused how we can define variable for globally use.
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// do some work here with the database.
db.close();
}
});

Related

How to connect mongodb Replicaset in node.js

I have tried this:
const mongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:4000,localhost:4001/bookstore?replicaSet=myapp';
mongoClient.connect(url,(err,db)=>{
if(err){
return;
}
console.log('connected to the database');
})
But how to export the database object(db)? The db object can be get only in the callback. Could you please give me some advice?

Error when connecting to mongodb

I am using node-run-cmd package to start the mongodb server in my app.js file. I know this works because I can see the collections on Robomongo when my script is running as well as the mongod.exe in my list of running processes. The problem is trying to connect to the db called testDB. Below is the commented code.
//start mongodb server
//this works
var nrc = require('node-run-cmd');
var cmd = '..\\mongodb\\mongod --dbpath '+__dirname+'\\db';
nrc.run(cmd);
//setup
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
//connect to mongo
//this fails to connect to db testDB
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("connection successful");
}
else{
console.log(err.message)
}
});
Here is the err.message
failed to connect to server [localhost:27017] on first connect
Any idea what I am doing wrong here. My assumption is that the db connection is trying before the server has fully started but I am not completely sure.
EDIT:
so that's what it was, timing issue. I tried the following and it connected to the DB. Is there a graceful way of doing this other than what I have here?
function connect(){
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if (!err) {
console.log("connection successful");
}
else {
console.log(err.message)
}
});
}
setTimeout(connect, 10000);
You should use the callback in the node_run_cmd package (https://www.npmjs.com/package/node-run-cmd#callback-style).
Place your connect function inside the callback.
You will probably also want to only start express here as well.

Unable to connect to the mongoDB server. Error: [Error: connection closed]

This is my nodejs program it is giving an error:
var mongodb = require('mongodb');
var server = Server = require('mongodb').Server;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/prisync_mamy';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('urlAnalysis_mamy');
var cursor = collection.find({channel_name:'urlAnalysis_mamy'});
cursor.each(function (err, doc) {
if (err) {
console.log(err);
} else {
console.log('Fetched:', doc);
}
});
}
});
Error: [Error: connection closed]
but when i type mongo on terminal it is running fine.
In my case, the problem was file security on the new server and mongdb npm module files, so I had to use "chown" command to own all files and then run "npm install", after that MongoDB client worked properly.
The exception from running your code is
TypeError: db.collection is not a function
and that tells you the collection keyword do not exist in the variable db. Look at the mongodb npm page and you should do this:
var mongodb = require('mongodb');
var server = Server = require('mongodb').Server;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/prisync_mamy';
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
console.log("Connected successfully to server");
const db = client.db('prisync_mamy');
...
});

How to include and use connection.js file in node.js application of mongodb

connection.js
/**
* lets require/import the mongodb native drivers.
*/
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database';
/**
* Use connect method to connect to the Server
*/
MongoClient.connect(url,function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('users');
db.close();
}
});
I prefer to just connect mongodb in the app.js, and only keep the passwords or url in an external file. But if you're going to do it your way.
Assuming your instance of mongoDB is running, and you're using the native driver for node, your connect.js should look like this:
// Require
var MongoClient = require('mongodb').MongoClient, assert = require('assert');
// Location
var url = 'mongodb://localhost:27017/myproject';
// Connect
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
Then your app.js will require your connect.js. It should look something like this
var db = require('...path to connect.js');
Don't forget to include mongoDB drivers in all of your models, then export your models. You then import your models into each controller you use them in.

Setting up mongodb on Heroku with Node

On my local host, I have the following Node code to setup a mongoDB database name "dbname":
users.js:
var MongoClient = require("mongodb").MongoClient,
Connection = require("mongodb").Connection,
Server = require("mongodb").Server;
Users = function(host, port) {
var mongoClient = new MongoClient(new Server(host, port));
mongoClient.open(function (){});
this.db = mongoClient.db("dbname");
};
Users.prototype.getCollection = function (callback) {
this.db.collection("users", function (error, users) {
if (error) callback(error);
else callback(null, users);
});
};
Users.prototype.findAll = function (callback) {
this.getCollection(function (error, users) {
if (error) {
callback(error);
} else {
users.find().toArray(function (error, results) {
if (error) {
callback(error);
} else {
callback(null,results);
}
});
}
});
}
// Bunch of other prototype functions...
exports.Users = Users;
I like to put the above database functionality in one file, and then in my main server file require that file as follows:
server.js:
var Users = require("./users").Users;
var users = new Users("localhost", 27017);
users.findAll(function (err, user) {
// Do something
});
To have this working on localhost is pretty easy. In the command line, I just type the following:
$ mongod # to launch the database server
$ node server.js # to launch the web server
and it works fine. However, now I'm trying to push the whole thing onto Heroku with the mongolab addon
heroku addons:add mongolab
but the database is not running and I have no idea how to make it run. This tutorial explains how to setup mongodb with the mongolab URI, but that's not how my code works, I use a host and a port and I create a new server based on that. How should I change my code for it to work on the heroku app? I want to keep the database code in a separate file, with the prototype functions.
Follow the example here at the "MongoClient.connect" section.
Essentially, you will need to change this part of the code:
Users = function(host, port) {
var mongoClient = new MongoClient(new Server(host, port));
mongoClient.open(function (){});
this.db = mongoClient.db("dbname");
};
To use mongoClient.connect() instead of new MongoClient:
Users = function(url) {
MongoClient.connect(url, function(err, db) {
// Find better way to set this since this callback is asynchronous.
this.db = db;
});
};
If you are using node, I recommend using a library such as mongoose npm install mongoose to handle mongodb interactions. Look at my answer here for how to structure your schemas.
Helped by Xinzz's answer, here's the modified code, so that the mongodb database is initialized with a URI instead of host + port. That's how Heroku initializes the mongodb database, and that's why it wasn't working.
var mongodb = require("mongodb");
var MONGODB_URI = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || "mongodb://localhost", // Make sure to replace that URI with the one provided by MongoLab
db,
users;
mongodb.MongoClient.connect(MONGODB_URI, function (err, database) {
if (err) throw err;
db = database;
users = db.collection("users");
accounts = db.collection("accounts");
var server = app.listen(process.env.PORT || 3000);
console.log("Express server started on port %s", server.address().port);
});
The key here is to declare the variables db and users upfront, assign them a value in the asynchronous callback of the connect function of MongoClient and also start the app (app.listen(...)) in the same callback. Then later in the code I can do the following:
users.find().toArray(function (err, results) {
// Do something
});
I also gave up on all these prototype functions, since they did not really add much.

Resources