Command Error : ( MongoServerError: bad auth : Authentication failed ) - node.js

Really I am trying to do a mongoose connection from Mongo Atlas. I think that I have a cluster problem. Please check the code and give me an answer.
//db connection
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0.qyrzo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
console.log('db connect');

you can use the mongoose library
you can try using a standard declaration
mongoose.connect("mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0.qyrzo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority");
if you are on latest version of mongoose you don't need to add the optional parametes
{ useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 }
but you can add it makes no difference
mongoose.connect("mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0.qyrzo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });

Related

Mongo DB Atlas Mongoose credentials must be an object

After removing Mongoose-package and re-installing it again I got stuck with an error.
The error I get seems to conflict with the instruction on Mongo DB Atlas instruction. where to place username and password in the dbURI.
error:
MongoParseError: credentials must be an object with 'username' and 'password' properties
This is my connection:
const dbURI = "mongodb+srv://admin:mypass#cluster0.iujq0.mongodb.net/myApp?retryWrites=true&w=majority"
const options = {
auth: { authSource: 'admin'},
useUnifiedTopology: true,
useNewUrlParser: true,
}
mongoose.set('strictQuery', false);
mongoose.connect(dbURI, options)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err))
The error indicates to place the username and password to the option object
I use node v 19.3 and Mongoose 6.8.2.
const options = {
autoIndex: false, // Don't build indexes
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
};
mongoose.connect(uri, options)
According to the official Mongoose documents these are options-object.
You don't need to specify the username and the password in the connect method of mongoose since it has already been inserted in the URL itself. In another way, there is no need to add any options when connecting to your Atlas.
Here is an example:
const dbURI = "mongodb+srv://admin:mypass#cluster0.iujq0.mongodb.net/myApp?retryWrites=true&w=majority"
const options = {
auth: { authSource: 'admin'},
useUnifiedTopology: true,
useNewUrlParser: true,
}
mongoose.set('strictQuery', false);
mongoose.connect(dbURI, options)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err))

Deprecation warning when connecting to mongoose

I'm connecting to a mongoose db, and I get a deprecation warning every time I try to connect.
(node:14933) 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.
I set useUnifiedTopology to true but I'm still getting the error. What am I doing wrong and how can I fix it?
const mongooseOptions = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
};
const dbUrl = config.get('dbUrl');
await mongoose.connect(dbUrl, mongooseOptions);
The DeprecationWarning for useUnifiedTopology comes from the underlying mongodb driver. Any connections will need this setting to use the new connection management.
In agenda, pass in options:
const agenda = new Agenda({
db: {
address: 'mongodb://localhost:27017/agenda',
options: {
useUnifiedTopology: true,
useNewUrlParser: true,
}
}
})
It looks like agenda can also reuse an existing mongoose connection by passing in the underlying mongodb db, something like:
const agenda = new Agenda({
mongo: mongoose.connection.db('agenda-test')
})

How to create installation script for app build on node.js, which include installation of dump of data base (mongo) , installation of camunda server?

I am trying to build an installation script for an app which made on node.js. As of now, I have to manually install the database dump, run Mongo server, npm packages and run Camunda server. So, is there any way I can do all those things by running a single script.
Please bear with my silly question.
Thanks in advance
you can call mongodump command from nodejs as discussed here
about mongo server, you can start it in your app:
import { connect } from 'mongoose'; // MongoDB ORM
connect(conf.db[conf.env], {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then(() => console.log(`connected to ${conf.db[conf.env]}`))
I need to say above code is written in ES6, if you don't use it you need to set Babel or use older code style:
const mongoose = require('mongoose');
mongoose.connect('url/of/your/db', {
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}, function (error) {
if (error) { // do sth with error
}
console.log('connected successfully');
}
I hope it helps you with your problem

connection error while connecting to AWS DocumentDB through lambda

getting the following error while connecting to AWS DocumentDB from node.js through lambda
{"errorMessage":"ENOENT: no such file or directory, open
'rds-combined-ca-bundle.pem'","errorType":"Error","stackTrace":["Object.fs.openSync (fs.js:646:18)","Object.fs.readFileSync
(fs.js:551:33)","Object.
(/var/task/base/mongoose.base.js:8:13)","Module._compile
(module.js:652:30)","Object.Module._extensions..js
(module.js:663:10)","Module.load (module.js:565:32)","tryModuleLoad
(module.js:505:12)","Function.Module._load
(module.js:497:3)","Module.require (module.js:596:17)","require
(internal/module.js:11:18)","Object.
(/var/task/library/mongoLib/room.lib.js:1:84)","Module._compile
(module.js:652:30)","Object.Module._extensions..js
(module.js:663:10)","Module.load (module.js:565:32)","tryModuleLoad
(module.js:505:12)","Function.Module._load (module.js:497:3)"]}
here is my node js file in lambda
var ca = fs.readFileSync(path.join('./','rds-combined-ca-bundle.pem'));
var options = {
keepAlive: true,
poolSize: 30,
socketTimeoutMS: 30000,
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
useCreateIndex: true,
auth: {authdb: 'admin'},
useFindAndModify: false,
sslValidate: true,
sslCA:ca,
useNewUrlParser: true
}
var uri = 'mongodb://'+globalData.getConfigurationSettings("documentdb_username")+':'+globalData.getConfigurationSettings("documentdb_password")+'#'+globalData.getConfigurationSettings("documentdb_server")+':'+globalData.getConfigurationSettings("documentdb_port")+'/'+globalData.getConfigurationSettings("documentdb_db_name")+'?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred';
mongoose.connect(uri, options)
.then(() => console.log('Connection to DB successful'))
.catch((err) => console.error(err,'Error'));
It should be:
var ca = fs.readFileSync(path.join(__dirname + '/rds-combined-ca-bundle.pem'));
Or you can define :
import caBundle from "./rds-combined-ca-bundle.pem";
var options = {
............
sslCA:caBundle,
The error comes from ENOENT: no such file or directory, open 'rds-combined-ca-bundle.pem
it seems that file doesn't exist there. can you check the path? did you embed the cert with lambda?

How to auto reconnect if mongo connection fails in node.js using mongoose?

I have mongodb up and running in a docker container. I stop the container and node returns a MongoError. I restart the container and node continues to throw the same MongoError.
I would like for it to reconnect when there was an issue.
const uri: string = this.config.db.uri;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
autoReconnect: true,
},
mongoose.connect(uri, options).then(
() => {
this.log.info("MongoDB Successfully Connected On: " + this.config.db.uri);
},
(err: any) => {
this.log.error("MongoDB Error:", err);
this.log.info("%s MongoDB connection error. Please make sure MongoDB is running.");
throw err;
},
);
How do i setup mongoose to try and auto connect when there is a connection failure to mongodb.
I found my answer, instead of checking error events and reconnecting like others have suggested. There are some options you can set that will handle auto-reconnect.
Here are the set of mongoose options i am now using.
const options = {
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
}
You can test it works by starting and stoping mongodb in a container and checking your node application.
For furuther information refer to this part of the documentation. https://mongoosejs.com/docs/connections.html#options

Resources