Its is my SG Key :- SENDGRID_API_KEY="SG.....51BH23ao"
I tried to take SG Key in single, double and even without quotes. Still facing same probelm.
Error:
MongoParseError: Invalid connection string
\[nodemon\] app crashed - waiting for file changes before starting...
Code:
setMongodb() {
mongoose.connect((0, Env_1.env)().dbUrl, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Database connected");
}).catch((e) => {
console.log(e);
LoggingService_1.default.critical(e);
console.log('failed');
});
}
Related
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))
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.
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;
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.
I'm connecting to a MongoDB database using the mongoose library.
After running mongoose.connect() I'm creating a mongoose.connection.on('error') handler.
After the app starts, I stop the MongoDB service to simulate a 'lost-connection event'. The script outputs:
events.js:196
throw er; // Unhandled 'error' event
...
and my app crashes.
The on('error') handler never executes. Why not? Isn't that the point of this event handler: to handle errors that the MongoDB connection throws, to avoid the app crashing?
Expected behavior: if the MongoDB connection is lost, the app attempts to reconnect indefinitely.
What am I doing wrong?
Here's my full connection code:
function dbConnect() {
// Establish MongoDB connection
logger.debug(`Connecting to MongoDB database ${process.env.DB_SERVER}:${process.env.DB_PORT} database ${process.env.DB_DATABASE}...`)
// Set up connection string
const db_uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}#${process.env.DB_SERVER}:${process.env.DB_PORT}/${process.env.DB_AUTH_DATABASE}`
// Initiate connection:
mongoose.connect(db_uri, {
dbName: process.env.DB_DATABASE, // Connect to the specified database
useNewUrlParser: true, // Use new settings
useUnifiedTopology: true,
useCreateIndex: true,
autoIndex: process.env.DB_AUTO_INDEX, // Autoindex
reconnectTries: Number.MAX_VALUE, // Keep retrying forever (thanks https://stackoverflow.com/a/39684734/1502289 and https://stackoverflow.com/a/41923785/1502289)
reconnectInterval: 5000, // Time to wait between reconnection attempts
})
.then(() => {
logger.debug("MongoDB successful connection")
})
.catch((err) => {
logger.debug("MongoDB connection error", err)
})
const db = mongoose.connection
// Set up database event handlers:
db.on('error', function(err) { logger.error("Unable to connect to database. Error: " + err) } )
db.once('open', function() {
logger.debug('Mongoose database connection established.')
// Load common properties from database:
// ... [snip]
})
db.on('disconnected', function() {
logger.error('MongoDB disconnected. Attempting to reconnect...')
})
db.on('reconnected', function() { logger.debug('Mongoose reconnected.')})
}