mongodb don't want to connect from my device - node.js

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;

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

MongooseError: Operation users.insertOne() buffering timed out after 10000ms” in Mongo Db atlas

I am currently working with node and mongoDB
here is my code
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
mongoose
.connect(
`mongodb+srv://OmniBotBuilder:${process.env.DBPASS}${process.env.DBUSER}.kx2vg.mongodb.net/${process.env.DBNAME}?retryWrites=true&w=majority`,
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
)
.catch(() => console.error("Unable to connect to DB"));
mongoose.connection.on("connected", () => {});
const Schema = mongoose.Schema;
const omniGamesSchema = new Schema({
discordId: Number,
steamId: Number,
});
const omniGamesModel = mongoose.model("omniGamesSchema", omniGamesSchema);
const createNewUser = (discordId, steamId) => {
const newUserMap = new omniGamesModel({
discordId: discordId,
steamId: steamId,
});
newUserMap.save((err) => {
if (err) {
console.error(err);
}
});
};
export { createNewUser };
and the error i am getting is this one
MongooseError: Operation omnigamesschemas.insertOne() buffering timed out after 10000ms
at Timeout. (C:\Users\dahiy\OneDrive\Desktop\bots\omni-games\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
This issue normally is caused because:
wrong auth, by the meaning the mongo path string is wrong so maybe double check your pass and username
check the allowed IP to access the database from the mongo website, if you want it to be accessed from everywhere just use IP: 0.0.0.0/0
Your internet connection might be slow to the point it cannot connect to the DB
Hope you found this helpful! :)
You can open https://cloud.mongodb.com/
Click connect Goto the Connect your application
Select Driver Node.js version 4.1 leter
Copy the link which you have to show than paste this link to your
project .env file now try to run application connect Database and
check.

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.

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.

Getting error while connecting to mongoDB database using Node.js

I am getting the following error while connecting the mongoDB database present in MLAB using Node.js.
Error in DB connection : {
"name": "MongoNetworkError",
"errorLabels": [
"TransientTransactionError"
]
}
Here is my code:
var mongoose = require('mongoose');
const authData = {
"useNewUrlParser": true,
"useCreateIndex": true
};
//connecting local mongodb database named test
mongoose.connect(
'mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd',
{useCreateIndex: true, useNewUrlParser: true,useUnifiedTopology: true },
(err)=>{
if (!err)
console.log('MongoDB connection succeeded.');
else
console.log('Error in DB connection : ' + JSON.stringify(err, undefined, 2));
}
);
module.exports = mongoose;
Here my database is present inside MLAB but when I am tring to connect to that DB its throwing me that error. I need to connect to my database here.
"useCreateIndex": true and useUnifiedTopology: true is deprecated .
Try out the following code to connect your mongoDB database .
mongoose.connect('mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd', {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));
module.exports = mongoose;
Please add your current IP or 0.0.0.0 to whiteList following "main page > security section > network access > add IP" in MongoDB website.
I hope this helps.

Resources