Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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?

2 Answers

0 votes
by (106k points)

For mongoose connection 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'); 

};

0 votes
by (108k points)

You probably didn't have a mongod running and hence it is not listening for connections. To do that you just need to open another command prompt and run mongod. After that you have to rearrange your code so that the event handler can easily connect(without any delay) the call:

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');

};

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 5, 2020 in Web Technology by ashely (50.2k points)
+1 vote
2 answers

Browse Categories

...