Search code examples
node.jsmongodbexpressmongoosemongoose-web-server

Why can I not connect to the mongoose server


I have implemented the code below in a db.js file to require mongoose and connect to the mongoose server. The code is below which is in a db.js file

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

mongoose.connection.on('connected', function (){
console.log('Mongoose connected to ' + dbUEI); 
});

mongoose.connection.on('error', function (err){
console.log('Mongoose connection error:' + err); 
});
mongoose.connection.on('disconnected', function (){
console.log('Mongoose disconnected:'); 
});

I will get this error when I try to connect to mongoose

node:16880) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Mongoose disconnected:
Mongoose connection error:MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

So I changed the second line of code that is in the db.js file to the code below

mongoose.connect('mongodb://localhost:27017/CaribbeanDb', {useNewUrlParser: true})

after the changes... I now get this error below

Mongoose connection error:MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I have tried to do further research to solve the error. I came across some commands which are below. to input into git terminal to solve the issue, but the commands are not found within the terminal.

$ sudo rm /data/db/mongod.lock
$ sudo mongod --dbpath /data/db/ --repair
$ sudo mongod --dbpath /data/db/ --journal

Any suggestions .. as I am running out of ideas where I am going wrong?


Solution

  • Do you have MongoDB installed on your machine?

    Mongoose is an ORM, while MongoDB is the actual database which makes it a dependency for Mongoose.

    If you're on macOS, you can run:

    mongo -version
    

    If it spits back that you do not have it, install with Homebrew:

    brew install mongo
    sudo mkdir -p /data/db
    sudo chown -R `id -un` /data/db
    

    Start the MongoDB daemon:

    mongod