Mongo DB Atlas Mongoose credentials must be an object - node.js

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))

Related

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')
})

Failed to connect node.js app to MongoDB Atlas despite using the correct connection credentials

I'm trying to connect my node.js application to MongoDB Atlas but I keep getting a "Bad authentication error" and yes, I am using the current database user credentials.
Here is the snippet that's supposed to connect to MongoDB Atlas
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log('MongoDB Connected: ' +conn.Connection.host)
}catch (err) {
console.error(err)
process.exit(1)
}
}
My terminate shows me bad authentication and some key-pairs that look so:
{
ok: 0,
code: 8000,
codeName: 'AtlasError',
name: 'MongoError'
}
Any ideas why it is not connecting to MongoDB Atlas?
I finally singled out the problem, it was the MongoDB connection string. I was simply inserting my password in the password field without removing the angle brackets.

mongodb don't want to connect from my device

I face this problem for 2 weeks now ,I was able to connect to my mongodb cluster before but now when i try to connect it give me this error message (queryTxt ETIMEOUT keep-connect-ebnzp.mongodb.net) ,I ask someone to try connect it from his pc and it connected and when i try to connect locally it work fine so what is the problem
I use this url to connect
mongodb+srv://mohamed:<password>#keep-connect-ebnzp.mongodb.net/<dbname>?retryWrites=true&w=majority
mongodb config code
const mongoose = require('mongoose');
const db = process.env.MONGDB_URL;
const mongoDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
console.log('Mongo DB connected');
} catch (err) {
console.error(err);
process.exit(1);
}
};
image for error on my terminal
module.exports = mongoDB;

Cosmos DB with Mongoose - Initial connection closes but is fine after auto re-connect

I have a weird thing going on here: I'm connecting to Azure's Cosmos DB using Mongoose 5.9.7 with the following code:
const mongoose = require('mongoose');
(async () => {
mongoose.connection.on('disconnected', () => {
console.log(new Date().toJSON(), 'disconnected!')
})
mongoose.connection.on('error', e => {
console.log(new Date().toJSON(), 'error', e);
})
mongoose.connection.on('connected', () => {
console.log(new Date().toJSON(), 'connected!')
})
await mongoose.connect(
'mongodb://<DB_HOST>:<DP_PORT>',
{
dbName: <DB_NAME>,
auth: {
user: <DB_USER>,
password: <DB_PASS>,
},
ssl: true,
useNewUrlParser: true,
useFindAndModify: true,
useCreateIndex: true,
useUnifiedTopology: true,
}
)
})();
Now after pretty much exactly 10 seconds the client is disconnected. After another 10 seconds the auto re-connect kicks in, connects and then the connection stays stable. If I set useUnifiedTopology to false the initial connection stays alive without the disconnect after 10 secs.
Any idea what might be causing this behavior?
I tried to connect to my cosmos db by using the code you provided,then it worked and the connection stayed stable whatever I set useUnifiedTopology true or false.By the way,my node.js version is v12.16.2 and the version of mongoose is 5.9.12.
Set useUnifiedTopology:true:
Set useUnifiedTopology:false:
The false option of useUnifiedTopology will be removed in a future version and it maybe update the newer data with an older value,so set useUnifiedTopology:false is not a Long-term solutions.
UnifiedTopology:ture use a server selection loop and retry the operation one time in the event of a retryable error.More details please refer to this article.

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