How to connect to mongoDB Atlas using mongoose - node.js

I'm trying to connect to my cluster on mongoDB Atlas via Mongoose.connect(), but every time i try to connect i get an exception "MongoError: authentication fail"
I know MongoDB Atlas is new mongo as a service could it be not supported by mongoose yet?.

The answer in this related post is correct. You should:
not mix options with connection string (if done so)
make sure your IP you are running on is whitelisted and your network allows connections to Atlas
make sure the user has sufficient permissions
use the connection string as is provided by atlas and just provide it to
mongoose.connect(uri);

MongoError: authentication fails - It means your name or password or dbname is not correct -
uri sample -
const uri =
"mongodb+srv://<username>:<password>#firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
Suppose username is - najim & password is 1234 & dbname is pets (Note - default dbname is test but you can write whatever you want) then my uri will be with above credentails -
const mongoAtlasUri =
"mongodb+srv://najim:1234#firstcluster.4rc4s.mongodb.net/pets?retryWrites=true&w=majority";
to connect with moongoose
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected")
);
} catch (e) {
console.log("could not connect");
}

const mongoAtlasUri =
"mongodb+srv://<username>:<password>#firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected"),
);
} catch (e) {
console.log("could not connect");
}
const dbConnection = mongoose.connection;
dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
dbConnection.once("open", () => console.log("Connected to DB!"));

try {
mongoose.connect( uri, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));
}catch (error) {
console.log("could not connect");
}
this works fine , try it

"mongodb+srv://:#cluster0.vvkuk.mongodb.net/"
also in the atlas, in security go to network access, there will be small buttons edit and delete click on edit, and in the edit, there will to two options the first option is ADD CURRENT IP ADRESS & the second option will be ALLOW ACCESS FROM ANYWHERE
go for the first option & then click confirm

Related

Managing MongoDB databases connection Based on Users

Good Morning Everyone .
for my project I'm Using mongo Atlas DB + Nodejs + express js
Currently let say I have one customer and all his users(managed with local-passport-js) and data are managed inside one DB in my cluster.
I'm Interested managing my project a step forward and create multiple DB's one for each costumer .
every costumer will have a different DB managing his users and data.
this is my current connection to the Db:
const MongoUrl = `mongodb+srv://*myuser**:${process.env.password}#testdb.9unfjt9.mongodb.net/?retryWrites=true&w=majority`
mongoose.connect(MongoUrl,
{ useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> {
console.log('DB Connection, Successful')
})
.catch(err => {
console.log('Error connecting DB')
console.log(err)
})
How can I Create "Global" User Collection and determine which DB the user Associate to and load it.
Thanks !

MongooseError: Operation `therapists.find()` buffering timed out after 10000ms

I have seen this issue published in a few places however I still don't have a solution.
I am using a node server and can connect to my database correctly with a status of 1 for connected.
However when I send requests to the mongodb database, the request pends and times out.
I have tried adding my IP to mongodb, putting my connection in an async function. and also removing mongoose and re installing it.
My structure is like this
app
client
node_modules > mongoose 5.13.14
server
node_modules > mongoose 5.13.14
My connection to mongodb is like this.
mongoose.connect(process.env.MONGOOSE_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then(res =>{
console.log("Connected to Database")
}).catch(function (reason) {
console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
An example of an endpoint that fails is here.
router.get('/therapists', (req, res) => {
signUpTemplate.find({}, (err, result) => {
if (err) {
console.log(err)
} else {
res.status(200).send({
results: result
})
}
})
})
which results in error
MongooseError: Operation therapists.find() buffering timed out after 10000ms
Can someone help me please as I am really not sure what the solution is.
Thank you!

How to deal with connection lost to DB in NodeJS Express App

I am developing an express application which connects to a MongoDB database. It is possible that my express server looses the connection to database, but how should my express server react to this scenario? I prepared the following code where i check for a lost connection and then I kill the app.
const registerCustomer = async (req, res) => {
let validRegistrationCode;
try {
validRegistrationCode = await CustomerRegistrationCode.findOne({ code: req.body.code });
} catch (error) {
if (error instanceof MongoNetworkError || error instanceof MongooseServerSelectionError) {
console.error('Mongo | Mongoose Network Error occurred');
}
process.exit(1);
}
return res.json({ obj: validRegistrationCode });
}
For every access to the DB, I have to check for a connection error and I think this makes the code ugly. How can this be improved?
I think the failure of connection to mongoDB usually doesn't happen or it can also happen in case of network is loss, or your path, syntax is not correct and what you should do is check only once when setup mongoose to connect to your database, every time you save code nodemon will help you check if you have successfully connected
// connect model with database
const mongoose = require('mongoose');
async function connect() {
try {
await mongoose.connect('mongodb://localhost:27017/collections_clothes', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useCreateIndex: true,
});
console.log("Access Database Success!");
} catch (error) {
console.log("Access FAIL!");
}
}
module.exports = { connect };

Unable to fetch data from mongodb- atlas?

I am trying to fetch data from MongoDB-atlas using note.js which I have manually fed to the server.
The status of the collection on MongoDB-atlas sever is :
dbname: viit
collection name : viit_atts
also, I have whitelisted my id and I am able to connect to the server.
I started off by connecting to the server by using the command :
mongoose.connect("mongodb+srv://wimpy_cool:myPassWordGoesHere#cluster0-phqid.mongodb.net/test?retryWrites=true&w=majority",{},function(err,res)
{
if(err)
{
console.log("mongo lab server not connected");
console.log(err);
}
else
{
// console.log(res);
console.log("Connectd to mongolab db");
}
});
Now using mongoose I have declared schema and made a model and then use the find function to fetch the data.
var bodyParser = require('body-parser');
var mongoose =require("mongoose");
var express= require("express");
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
mongoose.connect("mongodb+srv://wimpy_cool:myPassWordGoesHere#cluster0-phqid.mongodb.net/test?retryWrites=true&w=majority",{},function(err,res)
{
if(err)
{
console.log("mongo lab server not connected");
console.log(err);
}
else
{
// console.log(res);
console.log("Connectd to mongolab db");
}
});
var viit_att_schema = new mongoose.Schema({
name : String,
no_of_present: Number,
no_of_absent: Number
});
var att_history_schema = new mongoose.Schema({
time : String ,
att_stats : String,
});
var viit_att= mongoose.model("viit_att",viit_att_schema);
var att_history = mongoose.model("att_history",att_history_schema);
var list_of_all_members;
var list_of_all_members_sorted;
viit_att.find({},function(err,viit_atts)
{
if (err) {
console.log("OH NO ERROR");
}
else
{
console.log("fetching data now");
console.log(viit_atts);
list_of_all_members=viit_atts;
// console.log(list_of_all_members[0]);
// console.log(list_of_all_members);
list_of_all_members_sorted = list_of_all_members.sort(function(a,b) {
return b.no_of_present - a.no_of_present ;
});
console.log(list_of_all_members_sorted);
}
});
app.listen( process.env.PORT || 3000 , function(){
console.log("SERVER 3000 HAS STARTED");
});
But the fetching doesn't seem to take place, the console says this :
D:\MY PROJECTS\WEB\club_attendence_website>node backend.js
(node:13076) DeprecationWarning: current URL string parser is deprecated,
and will be removed in a future version. To us
e the new parser, pass option { useNewUrlParser: true } to
MongoClient.connect.
SERVER 3000 HAS STARTED
Connectd to mongolab db
fetching data now
[]
[]
The problem was that the default connection string for MongoDB atlas has a default database name as test, and will search for the same in the cluster, hence even though it will connect, nothing will be fetched.
In order to learn how to explicitly mention the dbName refer to this link: Fail to connect Mongoose to Atlas
Hi I had the same issue!
Issue:
I created a mongoDb Atlas collection name is "main"; however when I connect my nodeJs using mongoose, the collection name from the callback became "mains".
Solution:
I changed my model name to "mains" and it worked.
Try this:
‍var viit_att= mongoose.model("viit_atts",viit_att_schema);‍
Try doing it like this:
viit_att.find({}).then(content => {
console.log("data was fetched");
console.log(content);
list_of_all_members=content;
// console.log(list_of_all_members[0]);
// console.log(list_of_all_members);
list_of_all_members_sorted = list_of_all_members.sort(function(a,b) {
return b.no_of_present - a.no_of_present ;
});
console.log(list_of_all_members_sorted);
})
.catch(err => { console.log("OH NO AN ERROR") })
I got into this same problem, what worked for me, was to specify a collection name when defining your mongoose models:
module.exports = mongoose.model('App', schema, COLLECTION_NAME)
Where COLLECTION_NAME must match the mongodb atlas collection name.
For me the problem was that I was unable to fetch or get data but the connection was established with the server and I found that the few problems that can occur are:-
1: URL encoding
The text you put inside the connection string must be url encoded as said in the mongodb docs.
So, if the parameters you put inside the connection string like your database name or your password, the special characters that are : / ? # [ ] # must be url encoded (also known as percentage encoded), e.g. # becomes %40. You can use a bunch of online url encoders which are available on the internet.
2: Not added IP address from mongodb UI
You have to add the IP address of the computer from which the database will be sent a request. You can either do it in the first step while connecting by clicking 'Connect' on the cluster page or add ip address from here.
I personally kept it to be accessible by everyone, so added the ip address 0.0.0.0/0 (includes your current IP address).
3: Not specifying the correct database name
If you paste the default connection string in your app, it will point to the default database that is test. You will have to either change test to your db name or if there's nothing written, you'll have to write your db name
So, your connection string should look like this:-
mongodb+srv://<Your username>:<Your password>#cluster0.ezmvoas.mongodb.net/<Your db name>?retryWrites=true&w=majority
Troubleshoot
If there is any other problem, what you can do is to give error as an input to the callback function and try logging the error on the console.
const connectToMongo = () => {
mongoose.connect(mongoURI, (error, result) => {
console.log('Connected to MongoDB' + '\nError: ' + error);
});
}
By this way, you can get the fix for exactly the error message without trying different things.
Hope this solves the problem,
Thanks!

How to reconnect mongoose to another remote server?

I am totally new to node.js and mongoose, how to reconnect mongoose to another remote server ?
At the beginning of the file I have
var mongoose = require('mongoose')
and connected to localhost,
later in code I have
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
mongoose.createConnection(uristring, mongoOptions, function (err, res) {
if (err) {
console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
} else {
console.log ('Successfully connected to: remote' + uristring);
}
});
and I always get Successfully connected to: remote but when I bellow that print look for document by id I get always from local database(I have schema imported like require Person = mongoose.model('Person');).
How to reconnect to remote if I already have connection to local.
There are two ways of initializate a connection in mongoose:
Using the default connection "object"
Creating a connection from the dust
Here you are creating a connection, but using a model from another. Models are tied to databases (normal databases, replica sets or clusters) so you're not accesing to the correct host.
You must use the default connection (using mongoose.connect instead of mongoose.createConnection) or create a model in that new connection you are using. In your example:
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
var newConnection = mongoose.createConnection(uristring, mongoOptions);
newConnection.model(/*whatever*/);
mongoose.model wires to mongoose.connection. That is not the new connection you have created.

Resources