Mongoose parser error while connecting with mongoDB atlas - node.js

while trying to connect with my mongoDB atlas using mongoose connect method in node js I'm getting below mentioned parser error, I've checked my DB credentials and there are no special characters (:, /, ?, #, [], #) present in it.
Error:
MongoParseError: URI malformed, cannot be parsed
Code:
const mongoose = require('mongoose');
const DB = process.env.DB.replace('<password>', process.env.DB_PASSWORD);
mongoose
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connections);
console.log('DB connection successful!');
});

Related

How to find the Mongodb credentials from the config file?

I've recently joined to a project that uses Mongodb. I'm a newbie to this database. I need to find the database credentials to get an export of it (as a backup) before everything.
The doc says, the connect() method would have these parameters:
connect(url, user, password)
But I don't see that syntax in the real project. Here is the content of mongoose.js file:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(
'mongodb://bpAdmin:Bp1400##32.150.189.207:27017/bpDB?authSource=admin',
{
useCreateIndex: true,
useFindAndModify: true,
useNewUrlParser: true,
useUnifiedTopology: true,
autoIndex: true,
}
);
mongoose.set('useCreateIndex', true);
module.exports = {
mongoose,
};
(The IP and some other names just changed because of some security reasons)
Could you please tell me what's the user and password and db name?
Check out the format in offical documentation on connection string,
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
So for your questions,
info
value
username
bpAdmin
password
Bp1400#
db name used for auth
admin
default db to connect to
bpDB

MongoDB can be connected with MongoClient but not mongoose

So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.

Can't connect to MongoDB through heroku but works on localhost

Trying to push my simple notes app to heroku but when launched on heroku mongoDB gives me this error
Could not connect to any servers in your MongoDB Atlas cluster.
My backend works perfectly fine while my app is running locally and I have whitelisted all IPs in mongoDB and added MONGODB_URI as a local var in heroku so I'm unsure what is wrong at this point.
Here is my connection.
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('Connecting to..', url)
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
.then(result => {
console.log('Connected to MongoDB')
})
.catch((error) => {
console.log(`Error connecting to MongoDB: `, error.message)
})
Fixed the problem by deleting my whitelist in mongoDB Atlas and then adding it back, my server connected on heroku after that.

Unable to establish a mongodb atlas connection

I've tried connecting a MongoDB cloud atlas using URL in my Node application,but getting the following error:-
UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-coypu.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19)
Ive connected using:-
mongoose.connect(process.env.MONGODB_URI || config.connectionString, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = global.Promise;
In order to check whether the connection is established or not ive donw using:-
mongoose.connect('config.connectionString',{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
}).then(
() => {
console.log("Database connection established!");
},
err => {
console.log("Error connecting Database instance due to: ", err);
}
);
where config.connectionString contains the URL generated in my atlas.
mongoose
.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
log.info("successfully connected to db");
})
.catch((err) => {
log.error("db connection failed " + err);
});
Just make sure the URI is in correct format

Problem connecting to MongoDB Atlas cluster with mongoose (NodeJS)

I've been struggling to connect to my mongodb atlas cluster through mongoose. I'm still fairly new to nodejs, but after searching around all I could find was to set the flag to
useNewUrlParser: true and my own compiler threw a warning for me to add useUnifiedTopology: true. However it keeps getting caught as an error. Thanks for any advice or direction
Update: when outputting err, i get
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
going to dig into this now
//THIS IS PART OF .ENV
ATLAS_URI=mongodb+srv://myusername:mypw#cluster(:idhere).mongodb.net/test?retryWrites=true&w=majority
//THIS IS PART OF SERVER.JS
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const uri = process.env.ATLAS_URI;
// console.log('URI = "' + uri + '"'); //outputs correct URI
//without these two flags, get deprecated warning
mongoose.connect( uri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(err => {
console.log('URI error'); //still goes into here
});

Resources