简体   繁体   中英

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

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

I think you just have to replace your

db.on('connected', ..)

to

db.once('connected', ..)

You can also have something like this :

mongoose.connection.once('connected', function(err) {
    if (err) {
        console.log(err);
    }
    else {
        console.log("Connected to Database");
    }
}).on('error', function (err) {
    console.log(err);
}).on('disconnected', function () {
    console.log('Disconnected to database');
});

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM