Trying to connect to the mongodb free database on mongodb-atlas
I've almost tried everything Checked the docs, Changed the url, Changing password and even deleted the user and created the new one but still not resolve the problem
here is myurl.js file
module.exports = {
mongoURL: "mongodb+srv://nansDB:nansDB123#nodecluster-qs6cv.mongodb.net/test?retryWrites=true&w=majority",
secret: "mystrongsecret"
}
here is my index.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
//mongodb Configuration
const db = require('./setup/myurl').mongoURL;
//attempt to connect to database
mongoose.connect(db, { useNewUrlParser: true })
.then(()=> console.log('MongoDb Connect successfully'))
.catch(err => console.log(err));
const port = process.env.PORT || 3000;
here are the error lines I'm getting whenever I tried to run
{ MongoNetworkError: failed to connect to server [nodecluster-shard-00-02-qs6cv.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to nodecluster-shard-00-02-qs6cv.mongodb.net:27017 closed]
at Pool.<anonymous> (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\topologies\server.js:431:11)
at Pool.emit (events.js:189:13)
at connect (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\pool.js:557:14)
at callback (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:109:5)
at runCommand (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:129:7)
at Connection.errorHandler (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:321:5)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at TLSSocket.<anonymous> (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connection.js:350:12)
at Object.onceWrapper (events.js:277:13)
at TLSSocket.emit (events.js:189:13)
at _handle.close (net.js:597:12)
at TCP.done (_tls_wrap.js:388:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Its solved actually my whitelisted ip was changed because of connection issue [reconnecting to wifi]. Although my suggestion is checked whether the ip you whitelisted is exists or not.
Related
I have a droplet in Digital Ocean that is running MongoDB (4.0.3) and Ubuntu (18.04). I created this with their one-click formation. I followed the digital ocean tutorials to secure mongodb and to configure remote access. Everything works great if I ssh into the box and use the mongo shell. However, I am having trouble establishing a connection to the server from my laptop via nodejs/mongoose.
Can you help me figure out what is incorrect with my configuration? Or help me interpret the error messages
Here is what is working:
[terminal] - ssh into the box and use mongo shell
[node] - using tunnel-ssh I can establish a connection to the remote server
[node] - using the npm mongodb package I can create a connection to the database
However, I am unable to make a connection with mongoose using tunnel-ssh. Here is the code I am trying:
const mongoose = require('mongoose')
const tunnel = require('tunnel-ssh');
const config = {
username: 'user',
password: 'pass',
host: 'myLaptopIp',
port: 22,
dstHost: 'severRunningMongo',
dstPort: 27017, // this was open via `sudo ufw allow from myLaptopIp to any port 27017`
localHost: '127.0.0.1',
localPort: 27017
};
tunnel(config, (error, server) => {
if (error) {
console.log('SSH connection error: ' + error);
}
const url = 'mongodb://${dbuser}:${dbpass}#127.0.0.1:27017/${dbname}';
mongoose.connect(url, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
console.log('DB connection successful');
});
});
The error I am getting is
Error: connect ECONNREFUSED myLaptopIp:22
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16)
Emitted 'error' event on Server instance at:
at Client.emit (events.js:311:20)
at Socket.<anonymous> (/~/node_modules/ssh2/lib/client.js:294:10)
at Socket.emit (events.js:311:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: 'myLaptopIp',
port: 22,
level: 'client-socket'
}
If I change the localPort to 2000 OR if I change the mongo connection url to include the mongoServerIp, I get the error:
MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16) {
name: 'MongoNetworkError'
You know when you ask a question and then 1 minute later you think of something new to try, and that new thing completely works?
I think I don't need to use tunnel-ssh at all because I already opened the server to allow remote access from my laptop. This works for me
const mongoose = require('mongoose')
const url = 'mongodb://{dbUser}:{dbPass}#{mongoServerIp}:27017/{dbName}?authSource=admin';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
console.log('DB connection successful');
});
I did need to add the ?authSource=admin to the end of the url or it wouldn't work. I added my dbuser to the admin db as suggested in DO tutorial
I'm still not sure why the tunnel doesn't work, I would have expected it to still work?
I tried to connect MongoDB through mLab.com. It got redirected to MongoDB Atlas. I created one project and cluster. When trying to connect I get the Bad Authentication error, though my credentials are correct.
Password holds special characters. I tried replacing those special characters with ASCII hex code as well, but no response.
I replace my password in the below code
config/keys.js
module.exports = {
mongoURI: `mongodb+srv://Nikhilesh:<password>#devconnector-gicbg.mongodb.net/test?retryWrites=true`
};
server.js
const mongoose = require("mongoose");
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("DB Connected"))
.catch(e => console.log(e));
Result:
{ MongoError: bad auth Authentication failed.
at _authenticateSingleConnection (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\auth\auth_provider.js:46:25)
at sendAuthCommand (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\auth\scram.js:214:18)
at Connection.messageHandler (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connect.js:334:5)
at Connection.emit (events.js:182:13)
at processMessage (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connection.js:364:10)
at TLSSocket.<anonymous> (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connection.js:533:15)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
ok: 0,
errmsg: 'bad auth Authentication failed.',
code: 8000,
codeName: 'AtlasError',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }
Downgrade your mongoose to 5.4.6.
Below mongoose connect set of codes, add
mongoose.Promise = global.Promise;
Let me know if it works.
I am not able to solve the mongodb connection problem. I am getting the error below on starting node app.
Here is my mongoose connection code.
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/ml').then(
() => { console.log('Connected to mongodb!') },
err => { console.log('Failed to connect to mongodb'); console.log(err); }
);
module.exports = {mongoose};
Here is the error.
Started up at port 80
Failed to connect to mongodb
{ MongoNetworkError: failed to connect to server [10.160.0.2:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 10.160.0.2:27017]
at Pool.<anonymous> (/home/shivamsharma_btp2/mlsever/magguland/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at Pool.emit (events.js:189:13)
at Connection.<anonymous> (/home/shivamsharma_btp2/mlsever/magguland/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (/home/shivamsharma_btp2/mlsever/magguland/node_modules/mongodb-core/lib/connection/connection.js:246:50)
at Object.onceWrapper (events.js:277:13)
at Socket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Here are firewall rules of my google cloud app.
Got solution!
Use sudo before the command to start server.
I'm trying to create a simple rest API with a mongodb.
I have a server.js file
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-Parser');
const app = express();
app.use(bodyParser.json());
const db = require('./config/keys').mongoURI;
mongoose
.connect('mongodb://test:test123#ds241012.mlab.com:41012/mern_shopping')
.then(() => console.log('DB Connected'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started'));
I'm using nodemon
When I run npm run server I get the following error
(node:65209) 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.
then I got error in console
failed to connect to server
How do I fix this
Update
With {useNewUrlParser: true} the server starts but if I touch the server.js file I get this.
Server started
{ MongoNetworkError: failed to connect to server [ds241012.mlab.com:41012] on first connect [MongoNetworkError: connection 0 to ds241012.mlab.com:41012 timed out]
at Pool.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/connection/connection.js:257:10)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:420:8)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Here is the error message which i got while trying to run the project using gulp. I guess the problem is caused because of mongodb.
Gulp is running my app on PORT: 8000
events.js:160
throw er; // Unhandled 'error' event
^
MongoError: failed to connect to server [localhost:27017] on first connect
[MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\H SHASHANK
KUMAR\Desktop\code\node_modules\mongodb-core\lib\topologies\server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (C:\Users\H SHASHANK KUMAR\Desktop\code\node_modules\mongodb-core\lib\connection\pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (C:\Users\H SHASHANK
KUMAR\Desktop\code\node_modules\mongodb-
core\lib\connection\connection.js:187:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Below is the code which may contain the error.
var express = require('express')
mongoose = require('mongoose'); // creating reference for express
var db = mongoose.connect('mongodb://localhost/bookAPI'); //using mongoose
to connect to mongo db.
var Book = require('./models/bookModel'); //mongo db uees models to retrive
data.
var app = express(); // creating an instance of express to run app.
var port = process.env.PORT || 3000;
var bookRouter = express.Router();
bookRouter.route('/Books')
.get(function(req, res){
Book.find(function(err, books){
if(err)
console.log(err);
else
res.json(books);
});
});
app.use('/api', bookRouter);
app.get('/', function(req, res){
res.send('welcome to my API');
});
app.listen(port, function(){
console.log('Gulp is running my app on PORT: '+port);
});
I have tried searching for the error in other possible post on stack overflow but i didn't find any fix for my problem.