Just to be clear, I want to get MongoError bad auth Authentication failed from MongoDB Atlas.
This is about wrong DB password and I'm trying to catch that error and act accordingly.
this is my connection method:
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
});
and here I'm catching unhandledRejection error that supposed to catch wrong auth:
process.on('unhandledRejection', err => {
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
If I put correct password, everything works fine and I'm connected to database.
But if I put wrong password, after 30 sec of waiting I get:
MongooseTimeoutError Server selection timed out after 30000 ms
...and this shouldn't suppose to work like that.
I should get MongoError (bad auth) immediately, on first attempt when app is connecting to MongoDB
...or am I doing something wrong?
It's known issue for Mongoose <=5.7.1 with useUnifiedTopology: true option.
Update your Mongoose to 5.9.2 to fix the issue.
With new version, Mongoose fails corectly:
MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed.
at new MongooseServerSelectionError (D:\myapp\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (D:\myapp\node_modules\mongoose\lib\connection.js:808:32)
at Mongoose.connect (D:\myapp\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (D:\myapp\app.js:46:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'Authentication failed.',
name: 'MongooseServerSelectionError',
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
},
[Symbol(mongoErrorContextSymbol)]: {}
}
Also, add .catch clause to your code
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
})
.catch(error => {
//MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed
console.log("Error", error)
});
Related
I'm trying to connect to a MongoDB Atlas database with typeORM in an express project but I'm getting a 'Unescaped slash in userinfo section' error. My password doesn't have any special characters that need to be encoded so I don't know what's going on.
import { DataSource } from "typeorm"
export const AppDataSource = new DataSource({
type: "mongodb",
host: "mongodb+srv://username:password#database.cluster.mongodb.net/?retryWrites=true&w=majority",
useNewUrlParser: true,
synchronize: true,
useUnifiedTopology: true,
logging: true,
ssl: true,
entities: [
"src/entity/*.ts"
],
subscribers: [],
migrations: [],
})
"use strict";
import express from "express";
import cors from 'cors';
import "reflect-metadata";
import { AppDataSource } from "./data-source";
AppDataSource.initialize().then(() => {
const app = express();
app.use(cors({
origin: ['http://localhost:3000'],
credentials: true // this will allow cookies to be sent accross domains
}));
app.listen(8080, () => {
console.log("Server is running on port 8080");
})
})
the error I'm getting :
return callback(new MongoParseError('Unescaped slash in userinfo section'));
^
MongoParseError: Unescaped slash in userinfo section
at parseConnectionString (D:\Personal\jamboit\backend\node_modules\mongodb\lib\core\uri_parser.js:627:21)
at connect (D:\Personal\jamboit\backend\node_modules\mongodb\lib\operations\connect.js:283:3)
at D:\Personal\jamboit\backend\node_modules\mongodb\lib\mongo_client.js:284:5
at maybePromise (D:\Personal\jamboit\backend\node_modules\mongodb\lib\utils.js:692:3)
at MongoClient.connect (D:\Personal\jamboit\backend\node_modules\mongodb\lib\mongo_client.js:280:10)
at Function.MongoClient.connect (D:\Personal\jamboit\backend\node_modules\mongodb\lib\mongo_client.js:426:22)
at D:\Personal\jamboit\backend\node_modules\typeorm\src\driver\mongodb\MongoDriver.ts:249:38
at new Promise (<anonymous>)
Just replace host params to url in DataSource options
export const AppDataSource = new DataSource({
type: "mongodb",
url: "mongodb+srv://username:password#database.cluster.mongodb.net/?retryWrites=true&w=majority",
useNewUrlParser: true,
synchronize: true,
useUnifiedTopology: true,
logging: true,
ssl: true,
entities: [
"src/entity/*.ts"
],
subscribers: [],
migrations: [],
})
What is wrong with this setup
'''
nodejs
'''
require('dotenv').config()
// console.log(process.env)
const express = require('express')
const app = express()
const expressLayouts = require("express-ejs-layouts")
const indexRouter = require('./routes/index')
const mongoose = require('mongoose');
app.set("view engine", "ejs")
app.set("views", __dirname + "/views")
app.set('layout', "layouts/layout")
app.use(expressLayouts)
app.use(express.static('public'))
app.use('/', indexRouter)
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/printshop',{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
const db = mongoose.connection
db.on('error', error=> console.log(error))
db.once('open', ()=> console.log('connected to mongogoose'))
app.listen(process.env.PORT)
im trying to connect to mongodb in my local network but suddenly this
error message
just out
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (E:\nodejs\node-server\node_modules\mongoose\lib\connection.js:825:32)
at E:\nodejs\node-server\node_modules\mongoose\lib\index.js:417:10
at E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (E:\nodejs\node-server\server.js:20:10)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10) {
reason: TopologyDescription {
queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
what the mean?
im looking for the log of "connected to mongogoose" but it doesnt show in console then the error comes
ECONNREFUSED ::1:27017
what is this mean?
if anyone had a problem like this you can fix it by changing the
mongoodb://localhost/
to
mongoodb://127.0.0.1/
Im getting this error when I'm connecting my MongoDB Atlas cluster to my application and I am not sure what how to fix this issue as I have whitelisted all IP addresses as well. The code and the error are shown below:
const express = require("express");
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());`
mongoose.connect('mongodb+srv://surpol:mypassword123#cluster0.kiwls.mongodb.net/mydb123?retryWrites=true&w=majority', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(err);
});
MongooseServerSelectionError: connection <monitor> to 54.156.90.92:27017 timed out
at NativeConnection.Connection.openUri (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/connection.js:828:32)
at Mongoose.connect (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/index.js:335:15)
at Object.<anonymous> (/Users/suryapolina/Documents/GitHub/Phaseify/backend/server.js:15:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'connection <monitor> to 54.156.90.92:27017 timed out',
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: 'atlas-wpf52v-shard-0',
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'cluster0-shard-00-00.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.kiwls.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: 8
}
}
I have a requirement where I have to connect two different databases on different remote servers with mongoose from my main server.
Now,I have done a bit of research and founded that we can connect multiple instance with mongoose and then can use useDb() to use the specific database.
Everything works fine when I am connecting it to 2 local database but when the database are remote and I am connecting it via IP it is giving authentication error.
I guess connections are getting mixed.
Below is my code that I am using which is working on local database:
mongoose.connect('mongodb://'+db.host+':'+db.port+'/'+db.dbname,{user: db.username, pass: db.password, useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false })
.then(() => {
console.log(`db connection successful`);
mongoose.connect('mongodb://'+db2.host+':'+db2.port+'/'+db2.dbname,{user: db2.username, pass: db2.password, useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false })
.then(() => console.log(`db connection2 successful`))
.catch((err) => logger.error("db connection2 error", err));
}).catch((err) => logger.error("db connection1 error", err));
When host is localhost everything works fine but when I change it with the IP of the server it throws authentication error.
'not authorized on db to execute command { find: "collection_name", filter: { basicDetails.applicationNumber: "5000" }, projection: {}, returnKey: false, showRecordId: false, lsid: { id: UUID("164bf515-cec6-470f-fewcfrv") }, $clusterTime: { clusterTime: Timestamp(158461230, 1), signature: { hash: BinData(0, 6210C6E1586CFDBDC), keyId: 12346890 } }, $db: "DB" }'
Connecting from the REPL works fine:
> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });
returns:
{ connections:
[ { base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'test',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
_events: {},
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: {} }
> connected # Yes!
undefined
But connecting from a Mocha test suite does not work:
var mongoose = require( 'mongoose' );
console.log( 'connecting...' );
mongoose.connect( 'mongodb://localhost/test', function( error ) {
if( error) console.error( 'Error while connecting:\n%\n', error );
console.log( 'connected' );
});
returns:
$ mocha
connecting...
0 passing (0 ms)
Does anyone know why this not working?
Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is
auto-exit to prevent "hanging" with an active loop
which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.
describe('test suite', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/test', function(error) {
if (error) console.error('Error while connecting:\n%\n', error);
console.log('connected');
done(error);
});
});
});