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));
Related
I can't connect to the local mongodb server running on localhost:27017 from my express application. I'm pretty sure that I haven't done anything wrong in the code I wrote as I've copied it from a tutorial. The code worked fine on that tutorial. And I've also made sure that the mongodb service is running. I've already created a database called "blog" from mongosh shell and inserted some data to a collection called "authors" on it. I've also installed the MongoDB Node Driver using "npm install mongodb" command. But whenever I try to run npm start, this error shows up and I can't run my application thereafter.
E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 195900556,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket.<anonymous> (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...
This is the code I wrote on database.js to create the connection to the local mongodb server.
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
let database;
async function connect() {
const client = await MongoClient.connect("mongodb://localhost:27017");
database = client.db("blog");
}
function getDb() {
if (!database) {
throw { message: "Database connection not established!" };
}
return database;
}
module.exports = {
connectToDatabase: connect,
getDb: getDb,
};
This is the code I wrote on app.js to connect the database to it and run the application.
const path = require("path");
const express = require("express");
const blogRoutes = require("./routes/blog");
const db = require("./data/database");
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(blogRoutes);
app.use(function (error, req, res, next) {
console.log(error);
res.status(500).render("500");
});
db.connectToDatabase().then(function () {
app.listen(3000);
});
Your connect() function is not returning a Promise.
Try to change your code like this:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
let database;
async function connect() {
try {
await client.connect();
database = client.db('blog');
console.log('MongoDB connected...');
} catch (err) {
console.log('Error connecting to database...');
process.exit(1);
}
}
In your app.js just call the connectToDatabase function:
db.connectToDatabase();
app.listen(3000);
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.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: '1234',
server: 'AHMAD\SQLEXPRESS',
database: 'dbms_lab4',
port:1433,
encrypt:false
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Products', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
I can't connect to SQL Server. When I run the above program and access localhost:5000, nothing appears on the browser but a message on the terminal of vscode:
"The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules\mssql\lib\tedious\connection-pool.js:61:23
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at Immediate.<anonymous> (D:\JS\Sql_Connection\server.js:27:17)
at processImmediate (internal/timers.js:458:21) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}
ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at Connection.<anonymous> (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:428:26)
at Connection.emit (events.js:321:20)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at ConnectionError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
message: 'Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS',
code: 'ESOCKET'
},
name: 'ConnectionError'
}
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at D:\JS\Sql_Connection\server.js:27:17
at D:\JS\Sql_Connection\node_modules\mssql\lib\base\connection-pool.js:241:7
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}"
For SQL Connections: "Microsoft style strings of hostname\instancename are not supported."
EG from : https://www.w3schools.com/nodejs/nodejs_mysql.asp
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You need to update your config accordingly.
try escaping the \ in the server name
Change
server: 'AHMAD\SQLEXPRESS'
To
server: 'AHMAD\\SQLEXPRESS',
I have created the cluster on the MongoDB Atlas and now trying to create the db connect to it using the connection string provided on the Atlas.
My Connection String on key.js file:
module.exports = {
//mongoURI: "mongodb://DEVELOPER:DEV1234#devconnector"
mongoURI:
"mongodb+srv://USERNAME:PWD#devconnector-7dd46.mongodb.net/test?retryWrites=true"
};
Server.js file, DB Connect:
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDBConnected"))
.catch(err => console.log(err));
Error message:
{ Error: querySrv ESERVFAIL
_mongodb._tcp.devconnector-7dd46.mongodb.net
at errnoException (dns.js:55:10)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:243:19) code: 'ESERVFAIL', errno: 'ESERVFAIL', syscall: 'querySrv', hostname:
'_mongodb._tcp.devconnector-7dd46.mongodb.net' }
Just to add, I am getting the same error message while on trying to connect with Atlas from the Compass. Any help would be appreciated!
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