I am working on a small project(REST API) using nodeJs + MongoDB. I have been able to install MongoDB locally and connect to it using mongoose. However for some reason, when I try to connect using MongoDB Atlas it fails. It looks like it connects but then after 2 seconds, I get an error message saying sockets closed(see error below). I have no clue what is going on. I have whitelisted my IP, checked my login info to make sure I am using the correct password and indeed I am using because I am able to connect using MongoDB compass. Any help is greatly appreciated.
My current local ENV package versions are:
nodeJs:V9.7.1
mongoose:V6.1
=== MongoDb Atlas ===
mongodb:3.6
Below is the code that I am using to connect to the database:
var express = require('express'),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
user = require('./api/models/userModel'),
config = require('./api/config');
bodyParser = require('body-parser');
var authRoutes = require('./api/routes/authRoutes'),
userRoutes = require('./api/routes/userRoutes'),
reviewRoutes = require('./api/routes/reviewRoutes');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://user:myPass#cluster0-shard-00-00 zd6jq.mongodb.net/myDb');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Swagger Info
var options = {
explorer : true
};
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
//END Swagger Info
//REGISTER ROUTES
userRoutes(app);
authRoutes(app);
reviewRoutes(app);
app.listen(port);
console.log('iReview RESTful API server listenning on port: ' + port);
module.exports = app;
====ERROR MESSAGE ===
/Users/mdiez/node_test/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
MongoError: server cluster0-shard-00-00-zd6jq.mongodb.net:27017 sockets closed
at Pool.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/topologies/server.js:325:47)
at Object.onceWrapper (events.js:219:13)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/pool.js:101:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/connection.js:142:12)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at TCP._handle.close [as _onclose] (net.js:558:12)
var uri = 'mongodb://<usernamr>:<password>#<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(uri).catch((error) => { console.log(error); });
Specify the replica set name, ssl true and authentication database. This is based on reference from Atlas documentation.
You can use this code to connect to Compass and Application. You just need to the following:
replace all the three primary and secondary shard from Cluster -> Overview
replace natours-app with your cluster name.
Compass:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?authSource=admin&replicaSet=natours-app1-shard-0&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true
Application:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?ssl=true&replicaSet=natours-app-shard-0&authSource=admin&retryWrites=true
Related
Previously I tried to connect it by setting dbURI to the URI that mongo gives you upon clicking "connect application" and it did not work, later I tried to set up a local database with mongoDB, where i downloaded it, set it up and all the like. I created the data/db folder as well and i can open up an empty database upon typing the link in compass. Regardless of all of that, mongoose still doesn't allow me to connect to the database, giving me this error:
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (D:\tests\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (node:events:527:28)
at processIncomingData (D:\tests\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (D:\tests\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSSocket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}
Here's my code:
const express = require('express');
const mongoose = require('mongoose');
const CPD = require("./database/log");
// express
const app = express();
// database
const dbURI = 'mongodb://localhost:27017/local'
mongoose.connect(dbURI).then((res) => console.log("success")).catch((err) => console.log(err))
//serverstuff
app.get('/', (req, res) => {
res.send('Welcome!')
})
app.listen(3000);
try using '127.0.0.1' instead of 'localhost'
const dbURI = 'mongodb://127.0.0.1:27017/local'
I am currently trying to connect my Node container to my Mongo container using an M1 chip. Many have said that you can't run Mongo 4.9+ on an M1 Mac as there is no support for AVR. I can't say why but on my M1 mongo runs just fine. I can connect to the container via Mongo Compass using mongo://mongo:27017. Additionally if I run my Node app outside of docker I can connect to the Mongo container just fine using the same connection string. But for some reason I cannot connect the containerized node app to the containerized Mongo service.
Dockerfile
FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Copy dependencies
COPY package*.json ./
# Install dependencies
RUN npm install
RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 3000
CMD [ "node", "server.js" ]
docker-compose.yml
version: "2"
services:
web:
build: .
ports:
- "3000:3000"
depends_on:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
Connection Method
/* Mongoose Connection */
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect(
'mongodb://mongo:27017',
{ useNewUrlParser: true }
)
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection
Error:'))
mongoose.set('debug', true)
module.exports = mongoose.connection
server.js
require('dotenv').config();
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
var cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
app.use(cookieParser()); // Add this after you initialize express.
// db
require('./data/reddit-db')
// set db
const exphbs = require('express-handlebars')
// body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(expressValidator())
app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars')
var checkAuth = (req, res, next) => {
console.log("Checking authentication");
if (typeof req.cookies.nToken === "undefined" || req.cookies.nToken === null) {
req.user = null;
} else {
var token = req.cookies.nToken;
var decodedToken = jwt.decode(token, { complete: true }) || {};
req.user = decodedToken.payload;
}
next();
};
app.use(checkAuth);
// routes
require('./controllers/posts.js')(app)
require('./controllers/comments.js')(app)
require('./controllers/auth.js')(app)
require('./controllers/replies.js')(app)
// Start Server
app.listen(3000, () => {
console.log('Reddit Search listening on port localhost:3000!');
});
module.exports = app
Error
redditjspart2-web-1 | Reddit Search listening on port localhost:3000!
redditjspart2-web-1 | MongoDB connection Error: { MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
redditjspart2-web-1 | at Pool.<anonymous> (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js:438:11)
redditjspart2-web-1 | at Pool.emit (events.js:198:13)
redditjspart2-web-1 | at createConnection (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:561:14)
redditjspart2-web-1 | at connect (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:994:11)
redditjspart2-web-1 | at makeConnection (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:31:7)
redditjspart2-web-1 | at callback (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:264:5)
redditjspart2-web-1 | at Socket.err (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:294:7)
redditjspart2-web-1 | at Object.onceWrapper (events.js:286:20)
redditjspart2-web-1 | at Socket.emit (events.js:198:13)
redditjspart2-web-1 | at emitErrorNT (internal/streams/destroy.js:91:8)
redditjspart2-web-1 | at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
redditjspart2-web-1 | at process._tickCallback (internal/process/next_tick.js:63:19)
redditjspart2-web-1 | name: 'MongoNetworkError',
redditjspart2-web-1 | [Symbol(mongoErrorContextSymbol)]: {} }
What I Have Tried:
Running the same repo on an intel mac (works flawlessly)
Changing the connection string IP (mongo, localhost, 127.0.0.1)
Using a docker network with the bridge driver and using the assigned ip in the connection string
pinging mongo from inside Node container (this works and all packets are received)
The error says that it's trying to connect to 127.0.0.1:27017 which means it is properly resolving the hostname and mapping it to my localhost. So the Node container is definitely able to find it. This also makes sense because I can still ping the Mongo container from the Node container as I mentioned earlier. Looks like Mongo is just refusing to connect for some reason.
I am really struggling to figure out why this would be the case. The link to my repo is public and you can find it on github here: https://github.com/lukeaparker/reddit.jspart2
Thanks so so much!!
I had a similar issue with the M1 Mac and managed to resolve it by putting these configs in docker-compose.yml:
services:
mongodb:
image: arm64v8/mongo:4.0
platform: linux/arm64/v8
I also use docker build --platform linux/arm64/v8 and docker run --platform linux/arm64/v8 via CLI for platform explicitness since I got this warning previously:
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
I had the same issue.
As I see the issue is only with mongo 5+.
I was trying the downgrade the mongo image to
image: mongo:4.4.14
I am following a tutorial and trying to connect to mongodb, i have two files
the first is server.js with the following codes
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//DB config
const db = require('./config/keys').mongoURI;
//connect to mongo
mongoose
.connect(db,{ useNewUrlParser: true })
.then(()=>console.log('Connected to mongodb...'))
.catch(err=>console.log(err));
const port = process.env.PORT || 5000;
app.listen(port,()=>console.log(`server connected on port ${port}`));
The second is the config file
module.exports = {
mongoURI:'mongodb+srv://denis:password#shoppingapp-wmnbw.mongodb.net/shopping?retryWrites=true&w=majority'
}
what I am trying to achieve is to show on the console connected to mongodb...
instead I am given this error message
server connected on port 5000
(node:35030) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [shoppingapp-shard-00-01-wmnbw.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to shoppingapp-shard-00-01-wmnbw.mongodb.net:27017 closed
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:372:9)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)]
at Pool.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:310:20)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:561:14
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:1008:9
at callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:97:5)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:124:7
at _callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:349:5)
at Connection.errorHandler (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:365:5)
at Object.onceWrapper (events.js:417:26)
at Connection.emit (events.js:310:20)
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:370:12)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)
I have tried to change the driver version but still get the errors, where am I going wrong?
It turns out I was not connecting with the right IP address.
I am pretty new to node.js,am trying to write data to a free online mongo db atlas using mongoose,however i keep getting Authentication failed despite editing mongo db settings to connect from anywhere and also using correct username and password for the db user.
Here is my app.js file where i connect to mongo db
app.js:
const express = require('express');
const morgan = require('morgan');
const bodyParser= require('body-parser');
const mongoose = require('mongoose');
const app = express();
const productRoutes= require('./api/routes/products');
const ordersRoutes= require('./api/routes/orders');
mongoose.connect('mongodb+srv://hilary:'+process.env.MONGO_ATLAS_PW+'#node-rest-dnqwa.mongodb.net/test?retryWrites=true').catch(err => console.log(err));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use((req,res,next) =>{
res.header("Access-Control-Allow-Origin","*");
res.header('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept,Authorization');
if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,PATCH');
return res.status(200).json({});
}
next();
});
app.use('/products',productRoutes);
app.use('/orders',ordersRoutes);
app.use((req,res,next) => {
const error= new Error('not found');
error.status = 404;
next(error);
});
app.use((error,req,res,next) =>{
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
})
})
module.exports = app;
i get this error in my terminal:
{ MongoError: authentication fail
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\replset.js:1430:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:877:7
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:853:20
at finish (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:174:16)
at handleEnd (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:184:7)
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:289:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:544:18
at process._tickCallback (internal/process/next_tick.js:112:11)
name: 'MongoError',
message: 'authentication fail',
errors:
[ { name: 'node-rest-shard-00-00-dnqwa.mongodb.net:27017',
err: [MongoError] },
{ name: 'node-rest-shard-00-02-dnqwa.mongodb.net:27017',
err: [MongoError] } ] }
I am certain am using correct name and password so why cant it authenticate me,server runs on my localhost
EDIT
So i followed link to docs and now connect this way:
mongoose.connect('mongodb://hilary:'+process.env.MONGO_ATLAS_PW+'#localhost:27017/test').catch(err => console.log(err));
I then get this error in terminal:
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\server.js:505:11)
at Pool.emit (events.js:180:13)
at Connection.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:329:12)
at Object.onceWrapper (events.js:272:13)
at Connection.emit (events.js:180:13)
at Socket.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:272:13)
at Socket.emit (events.js:180:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:114:19)
name: 'MongoNetworkError',
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
What worked was a slight variation from the mongoose docs,it was suggested on the Atlas server,for everyone who has Mongodb 3.4+ connect using the regular mongo db driver even when using mongoose, my connection string looks like:
mongoose.connect('mongodb+srv://hilary:<password>#node-rest-dnqwa.mongodb.net').catch(err => console.log(err));
My app in nodeJS refuses to connect to the database when I run it, I am using mongoose ODM to connect to the database. When I run the application I get the error below.
Server running at port 8000
/Users/user/www/document-manager/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1065:14)
Below is the code which I run:
var express = require('express'),
mongoose = require('mongoose'),
dotenv = require('dotenv'),
bodyParser = require('body-parser'),
router = require("./server/router");
//Initialize App
var app = express();
app.use(bodyParser.json());
//Initialize database connection
mongoose.connect("mongodb://localhost/dms");
router(app);
//Load Dotenv
dotenv.load();
//Set Port
var port = process.env.PORT || 8080;
//Run applicatino
app.listen(port, function(){
console.log("Server running at port " + port);
});
The application would run if I run mongod from the terminal separately. Is there a way to run my database server and my application server together?