Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoNetworkError: connection 0 to localhost:27017 closed

I can´t get this to work. I have opened mongo and mongod, and this is what I get when I write "node server.js" in git Bash or cmd:

Running on server27017
Not connected to database MongoNetworkError: connection 0 to localhost:27017 
closed

and here is my code.

var express = require('express');
var app = express();
var port = 27017;

//Route
app.get('/', function (req, res) {
    res.send('Hello world!');
});


const mongoose = require('mongoose');
const option = {
    socketTimeoutMS: 30000,
    keepAlive: true,
    reconnectTries: 30000
};

mongoose.connect('mongodb://localhost:27017/database1', option).then(function(){
    //connected successfully
    console.log('Successfully connected to database');
}, function(err) {
    //err handle
    console.log('Not connected to database ' + err);
});

//Listen to port
app.listen(port, function(){
    console.log('Running on server' + port);
});

and when I write "http://localhost:27017/database1" in the browser I get "It looks like you are trying to access MongoDB over HTTP on the native driver port."

like image 717
helloRebecca Avatar asked Apr 19 '18 12:04

helloRebecca


2 Answers

Express port shouldnt be the same port with mongoose

like image 115
Bill Avatar answered Oct 25 '22 05:10

Bill


If you are connecting to mlab and this error is because you have to add your system IP address.

You can add your system's IP address in Network Access tab

like image 37
vba Avatar answered Oct 25 '22 06:10

vba