Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Connection

Tags:

I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.

var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test');  exports.test = function(req, res) {   var db = mongoose.connection;   db.on('error', console.error.bind(console, 'connection error:'));   console.log("h1");   db.once('open', function callback () {     console.log("h");   });   res.render('test'); }; 

This is my code. The console only prints h1, not h. Where am I wrong?

like image 362
CSnerd Avatar asked Dec 03 '13 20:12

CSnerd


2 Answers

When you call mongoose.connect, it will set up a connection with the database.

However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it).

You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:

var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () {   console.log("h"); });  exports.test = function(req,res) {   res.render('test'); }; 
like image 61
robertklep Avatar answered Sep 25 '22 07:09

robertklep


The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.

Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.

If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone!

Here's the code.

var mongoURI;  mongoose.connection.on("open", function(ref) {   console.log("Connected to mongo server.");   return start_up(); });  mongoose.connection.on("error", function(err) {   console.log("Could not connect to mongo server!");   return console.log(err); });  mongoURI = "mongodb://localhost/dbanme";  config.MONGOOSE = mongoose.connect(mongoURI); 
like image 40
fino Avatar answered Sep 24 '22 07:09

fino