Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
411 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...