Chelsea
Chelsea

Reputation: 11

Trying to connect node.js to a mongodb, getting successful response but no connection

I have been following online instructions to set up a mongodb database using mongoose on node.js. I have managed to get the mongodb running and listening on port 27017, however when I run my connection code in node.js I get a successful response even when the mongo.db isn't running and I don't see any updates on the mongo.db to say it has received any data.

I have tried quite a few different examples from the internet but can't get any of them to work.

So I have my MongoDB saying:

2019-03-26T12:00:46.039+0000 I NETWORK  [initandlisten] waiting for connections on port 27017

This is the basic code I am trying to get to work as my original API wasn't working:

//sample.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', function(err){

  if(!err) console.log('Successfully Connected');

  console.log(mongoose.connection.host);

  console.log(mongoose.connection.port);
});

I receive this response when I run

node sample.js

Successfully Connected

localhost

27017

But I receive this response even when my mongo.db has been shut down, so I think there is some error, I'm not sure how to check if they are connecting properly.

Upvotes: 1

Views: 1546

Answers (2)

jcuypers
jcuypers

Reputation: 1794

this works for me. try to set some debugging to find out what is happening.

mongoose.set('debug', true);

mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true})
    .then(() => {
        console.log('connected to the db');
     })
    .catch(err => {
        console.log('connection failed ' + err);
    }); 

Upvotes: 2

takrishna
takrishna

Reputation: 5002

I think you have to check the API to connect.

https://mongoosejs.com/docs/connections.html

Second parameter is option and third is callback - but u seem to have passed callback as second param - also, check what are you getting as response

mongoose.connect(uri, options, function(error) {
  // Check error in initial connection. There is no 2nd param to the callback.
});

// Or using promises
mongoose.connect(uri, options).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
  err => { /** handle initial connection error */ }
);

Upvotes: 1

Related Questions