2
votes

I am building a REST api service with Node, Express and MongoDB. I installed MongoDB and it runs normally on my PC on localhost:27017. I can add collections and read em. In my app.js file I have this setup


    var express = require('express');
    var mongoose = require('mongoose');
    var bodyParser = require('body-parser');

    mongoose.connect('mongodb://127.0.0.1:27017/bookAPI');

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
      console.log("h");
    });


    var app = express();
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());

    var port = process.env.PORT || 3000;

    app.use('/api', require('./routes/api.js'));



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

 

I always get an error- MongoError - cannot connect UNKNOWN I searched for hours and didn't find any solution. How can I fix it so it can connect to MongoDB, which is working properly...?

5
Do you have the mongod instance running on the same machine? Also, try mongodb://localhost:27017/bookAPIsnozza
I do have mongod running and also inserted some dummy data. I tested the same instanse on a different PC with Win7 installed and it worked. I found out later that XP is not supported by mongodb in the new releases.Georgi Arnaudov

5 Answers

1
votes

I solved this problem, with installing stable mongoose. It was mongoose 4.x, I've installed 3.8 (npm install [email protected].*) in winxp.

1
votes
const dbpath = "mongodb+srv://127.0.0.1/bookAPI";

// Data connection
mongoose.connect(dbpath, {user: 'username', pass: 'password', useUnifiedTopology: true , useNewUrlParser: true })
  .then(()=> console.log("Now connected to MongoDB!"))
  .catch(err=> console.error("Something went wrong", err));

I was using Compass and this piece of code works perfectly fine.

0
votes

Try to change:

mongoose.connect('mongodb://127.0.0.1:27017/bookAPI')

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

Into:

var appConnection = mongoose.createConnection('mongodb://127.0.0.1:27017/bookAPI');

appConnection.on('error', console.error.bind(console, 'connection error:'));
appConnection.once('open', function callback () {
  console.log("h");
});
0
votes

Try this one:

var connectionString = "mongodb://" + host + ":" + dport + "/" + dbName;
mongoose.connect(connectionString, function(err) {
    if (err) {
        console.log(err)
    } else {
        console.log('Connected to database ' +dbName);
    }
});
0
votes

mongoose.connect('mongodb://127.0.0.1/bookAPI');