Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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...?
–
–
// 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.
–
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");
var connectionString = "mongodb://" + host + ":" + dport + "/" + dbName;
mongoose.connect(connectionString, function(err) {
if (err) {
console.log(err)
} else {
console.log('Connected to database ' +dbName);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.