Connection to both mongodb atlas cluster and the local host - node.js

I have deployed my nodejs project to Heroku and have used the mongodb cluster url but I also want to work in my local machine and use the local host.
I tried writing this code for when it doesn't connect to the cluster it should connect to the local host but the problem is the atlas url doesn't return 'undefined' when not connected.So how to connect with both the atlas cluster and the local host.
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
require('dotenv').config();
const mlabDB = `mongodb+srv://${process.env.MLAB_USERNAME}:${process.env.MLAB_PASSWORD}#todo-app-qhj7g.mongodb.net/test?retryWrites=true&w=majority`;
mongoose.connect(mlabDB || 'mongodb://localhost:27017/TodoApp', {useNewUrlParser: true})
.catch((e) => {
console.log(e);
});
module.exports = {mongoose};

Within the code, there is a line:
mlabDB || 'mongodb://localhost:27017/TodoApp'
The variable mlabDB is not returning undefined, because you are defining mlabDB as:
const mlabDB = `mongodb+srv://${process.env.MLAB_USERNAME}...
In this case, if process.env.MLAB_USERNAME is undefined, the string will return:
mongodb+srv://undefined
In answer to your question: "how do I connect with both the atlas cluster and the local host?": use a JavaScript Ternary Operator:
const mlabDB = process.env.MLAB_USERNAME ? `mongodb+srv://${process.env.MLAB_USERNAME}:${process.env.MLAB_PASSWORD}#todo-app-qhj7g.mongodb.net/test?retryWrites=true&w=majority` : ``;
For more info on Heroku Config Vars, see here.
For local vars management, use npm's dotenv package.

Have you tried connecting them seperately? As I understand you want to connect them both at the same time. Try this:
mongoose.connect(mlabDB , {useNewUrlParser: true})
.catch((e) => {
console.log(e);
});
After you do everything needed with atlas do everthing again for your own database. Yes you have to connect them seperately and process.
mongoose.connect('mongodb://localhost:27017/TodoApp' , {useNewUrlParser: true})
.catch((e) => {
console.log(e);
});
If you want to connect your own database if atlas connection is not possible. Use console.log to see what atlas returns if connection is not happened. And add an if statement to check if connection is happened or not.

Related

AWS Lambda can't access mongoDB

I'm deploying simple express CRUD API with serverless framework. It works fine until it comes to accessing databese, it returns {"message":"Internal Server Error"}. But when running locally it works as intended. Is there a problem with the way I'm connecting to mongoDB?
const mongoose = require("mongoose");
const { logger } = require("../Log/pino");
require("dotenv").config();
mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_URI, {serverSelectionTimeoutMS: 5000});
const connection = mongoose.connection
.once("open", () => {
logger.info("connected to database");
})
.on("error", (err) => {
logger.info(`mongoose error: ${err}`);
});
module.exports = connection;
Fixed it. Problem was that I was only allowing access to mongoDB cluster to requests sent only from my IP. Changed cluster network access settings and it works now as it should.

Can't connect to MongoDB Server

My nodejs app can't connect to MondoDB Server.
I have already allowed all ip addresses (0.0.0.0/0) to connect.
const mongoose = require('mongoose');
const URL = '' //database url
mongoose.connect(URL, {useNewUrlParser: true}).then(db => {
console.log("Connected")
}).catch(err => {
console.log(err)
})
Above code throws "MongooseServerSelectionError: connection timed out" error
U have to provide URL in mongoose something like this
const url = 'mongodb://localhost:27017/myapp'
But before that please verify whether the mongo is running in your system or not.

Cannot connect to mongoDB Atlas using mongoose : { MongoNetworkError: failed to connect to server }

Although I am not the first on Stackoverflow not to be able to connect to mongoDB atlas using mongoose, no one seems to have my specific error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-00-shqnc.mongodb.net:27017] on first connect
[MongoNetworkError: connection 5 to
cluster0-shard-00-00-shqnc.mongodb.net:27017 closed]
Here's how my server is set-up:
Keys.js
module.exports = {
mongoURI:
"mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};
Server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true
})
.then(() => {
console.log("MongoDB connected!");
})
.catch(err => {
console.log(err);
});
app.get("/", (req, res) => {
res.send("Hello");
});
//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And this is the code suggested by the MongoDB atlas website to be used:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
But, since I don't want to use mongoClient but rather mongoose, I am having some trouble and I cannot see why the code doesn't work;
EDIT 1: I have managed to connect using the Shell command(Check-out my answer). However, connecting through the app doesn't work and gives a different error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-01-shqnc.mongodb.net:27017] on first connect
[MongoError: bad auth Authentication failed.]
EDIT 2: I made a stupid mistake. I've forgotten to remove <> from the . All is good now.
The problem is that I was trying to connect using my MongoDB Atlas account password instead of the user password. Yes, those are 2 different things.
1. Click on Database Access
2. Edit the current user and modify the password
3. Use that password to connect to MongoDB Atlas
Make sure you have whitelisted your public IP. You can find that by googling "what is my ip".

Can't connect to a MongoDB using Node.js

Can't connect to a MongoDB using Node.js.
This is my code (mdb.js):
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('mongodb://localhost:3000', function(err,db){
if(err){
throw err;
} else {
console.log("Connected");
}
db.close();
});
node mdb.js prints MongoError:
enter image description here
it worked for me when i changed 'localhost' to 127.0.0.1
First make sure your MongoDB server is running by running mongod in the directory that MongoDB is installed.
Then see what port it is running on ( usually it's 27017 ) . Then update your URL in your code and you're good to go .
Your error explaining itself.
Mongo cant find default db path B:/data/db.
Create this folder or on start up choose another DB directory
mongod --dbpath yourPath(C:\myDb)
Also default mongo port is 27017 so you need to change connection string like this "mongodb://#localhost:27017/dbYouWant"
Hope this helps.
Use this URL mongodb://0.0.0.0:3000
First of all please verify that have you changed your default database port from 27017 to 3000 or not.
If not changed then please try the below code it's working for me
const { MongoClient } = require("MongoDB");
// Connection URL
const url = "mongodb://localhost:27017";
const client = new MongoClient(URL);
// Database Name
const dbName = "myProject";
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection("documents");
// return "done.";
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
Also here is I attached a my screenshot with the output
Sample output example

mLab doesn't work on Heroku

I've added mLab to my Heroku app, I also use mongoose. I tried use connection string from localhost, and it was working(almost). In my server file I use:
var db = mongoose.connection;
if (process.env.MONGODB_URI) {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect('mongodb://localhost/fitMe')
}
If I open the app from localhost, it saves things to the db, and can get it back, although not everything, but on heroku it doesn't work at all. I use react with server. I think that something wrong with the routs.. so here is the link to server file :
https://github.com/HelenaVolskaia/Motivation/blob/master/server/app.js
You can set an env variable locally and only use this:
// Connect Mongo
mongoose.Promise = global.Promise; // mongoose promises deprecated, use node - mongoosejs.com/docs/promises
mongoose.connect(config.db.MONGODB_URI);
mongoose.connection.once('open', () => { console.log('MongoDB Connected'); });
mongoose.connection.on('error', (err) => { console.log('MongoDB connection error: ', err); });
But regardless, add the on connection error handler and see what the error is, so you can dig deeper into why it's not connecting.

Resources