Reputation: 427
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 them. 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've searched for hours and didn't find any solution. How can I fix it so it can connect to MongoDB, which is working properly...?
Upvotes: 2
Views: 2384
Reputation: 116
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.
Upvotes: 1
Reputation: 77
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);
}
});
Upvotes: 0
Reputation: 1955
I solved this problem, with installing stable mongoose. It was mongoose 4.x, I've installed 3.8 (npm install [email protected].*) in winxp.
Upvotes: 1
Reputation: 64
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");
});
Upvotes: 0