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.
Related
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.
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".
In local mongodb is running when i connect to mongodb atlas it is not connecting and there is no errors.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://NaveenS:naveen#frozenexpression-
jiptd.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, {useNewUrlParser: true,
useUnifiedTopology: true} );
client.connect(err => {
const collection = client.db("yelp_camp").collection("campgrounds");
client.close();
});
In uri your database name is test and you trying to connect 'yelp_camp' so write both same and try again.
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.
I'm trying to use mongoDB for my app.
I have 2 databases and use next code to connect:
var express = require("express");
var router = express.Router();
var mongojs = require("mongojs");
//var mongo_db =
//mongojs("mongodb://xxxxx:xxxxx#some_adress/cat_mean_db", ["tasks"]);
var mongo_db = mongojs("mongodb://xxxxx:xxxxx#localhost:3000/cat_db",
["tasks"]);
//get all docs(pages)
router.get("/tasks", function (req, res, next ) {
mongo_db.tasks.find(function (error, tasks) {
if(error)
res.send(error);
res.json(tasks);
});
});
if I use this db
var mongo_db =
mongojs("mongodb://xxxxx:xxxxx#some_adress/cat_mean_db",
["tasks"]);
everything is working well, but when I try to use db on localhost I got an exeption: connection 0 to localhost:3000 closed
the local db is exist and has user for shure.
From mongoose documentation on NPM :
Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.
You should try using 127.0.0.1 instead of localhost.