简体   繁体   中英

mongoDB connect (via Node.js driver) doesn't give me console log msg

I have this code on my server.js file. I want to connect to this mongoDB data base and then get a console log indication.

However, there is no console log message for the database connection (for the server I do get log message). I don't get even an error message, just one message to the console log that the http is connected (nothing on the database).

why? my code is below thanks

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app); 
var io = require('socket.io')(http);
var path = require('path');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

 //more code that is not relevant



var url = 'mongodb://1.0.0.127:4444/small-talkz';

MongoClient.connect(url, function(err, db) {
    console.log("Connected correctly to DB.");
    db.close();
});

http.listen((process.env.PORT || 3000), function(){
    console.log('listening on *:3000 '+ __dirname);
});

As noted in the docs of the Node.js driver, there is a default retry count of 5 and 5000 ms between each retry. So you have to wait a bit before you actually get an error in your callback. As you currently do not write the error to console , you won't see the error but get an error due to accessing db which is then null .

Change it to

MongoClient.connect(url, function(err, db) { 
    if (err) {
        console.log(err);
    }
    else {
        console.log("Connected correctly to DB.");
        db.close();
    }
});

and wait for a minute and you will see the error. Alternatively, decrease the retry count or the delay between each retry to see it faster failing :)

After you see the error you either will be able to see the reason and fix it (probably your URI is wrong) or at least you can provide us with more information.

Try with this to make connection. Run mongod with the default port 27017 & localhost.

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/table_name", function(err, db) {
    if(err)
    {
      console.log(err);
    }
    else{
      console.log("Connected correctly to DB.");
      db.close();
    }
  });
});

If its working with this, then make sure you are running mongo server on specific ip 1.0.0.127(weird ip) and on port 4444.

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