Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose callback hangs node js

I'm new to mongoose and javascript in general, and want to connect to a locally running mongodb. The following code give no errors, will perform all of the console logs except for the one inside the db.on('connected', function() call. The console log before that prints out a 1, and I can see on my mongodb terminal that a connection is being accepted. What am I missing here?

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rawStockData');

https.get(requestURL, function(res) {
  var data = '';
  res.on('data', function (chunk) {
    data += chunk
  });
  res.on('end', function() {
    var jsonObj = JSON.parse(data);
    console.log('Data Parsed');

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    console.log(db.readyState);
    db.on('connected', function() {
      console.log('ConnectedToDatabase!');
    });
  });
});
like image 795
Adam Kall Avatar asked Jul 16 '26 08:07

Adam Kall


1 Answers

In your case mongoose.connect is called before the event listeners are installed.

You attach the event listener for open at a much later point in time (when a request is being handled).

Try to edit your code and put the event listeners just after the connect function.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rawStockData');


var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.on('connected', function() {
   console.log('ConnectedToDatabase!');
});

https.get(requestURL, function(res) {
  var data = '';
  res.on('data', function (chunk) {
    data += chunk
  });
  res.on('end', function() {
    var jsonObj = JSON.parse(data);
    console.log('Data Parsed');
  });
});
like image 92
semanser Avatar answered Jul 18 '26 22:07

semanser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!