Error, While Connecting To Mlabs Using Node.js - node.js

I am Getting Error While Connecting My Node.js Application to Mlabs Database. I am Using the Below Code, Please Tell me Where I am Wrong.
var express = require('express');
var app = express();
const MongoClient = require('mongodb').MongoClient;
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11';
app.get('/', function(req, res) {
MongoClient.connect(MONGO_URL, { useNewUrlParser: true }, (err, db) => {
if (err) {
return console.log('Error While Connecting to mongodb');
}
db.collection("users").find({_id:"5b50e2d3e712fa3g8a8e9a76"}, function(err,result){
if(err){
console.log('Error While Finding data from your table');
}else{
console.log(result);
}
})
});
});
app.listen(process.env.PORT || 5000);
Thanks In Advance.

Using the same connection string in your code, I console.log the error and got "MongoNetworkError: failed to connect to server". To fix this, make sure the connection string
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11'
is correct
and also make sure that your network is fine and can connect to mlab.

Related

MongooseError: Operation `domains.insertOne()` buffering timed out after 10000ms

I understand that we need to use asynch and await while connecting db since models are loading before db connection happening so i have used and call the function in server.js Please look into my code and help me.
Connection.js
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
console.log(process.env.DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
//useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
Server.js
const express = require('express');
const dotEnv = require('dotenv');
const { urlencoded } = require('express');
const cors = require('cors');
const dbConnection = require('./database/connection');
dotEnv.config({path:'./.env'});
const app = express();
// Database connection
// cors
app.use(cors());
app.use(express.json());
dbConnection();
app.use('/api/v1/domain', require('./routes/domainRoutes') );
app.get('/', (req, res, next)=>{
res.send("Hello From node aPI server");
});
// request payload middleware
app.use(express.json);
app.use(urlencoded({extended:true}))
const PORT = process.env.PORT || 3000;
app.listen(PORT, ()=>{
console.log(`Server Listen on port ${PORT}`);
});
// error handling middle ware
app.use(function(err, req, res,next){
console.error(err.stack)
res.status(500).send({
status: 500,
message:err.message,
body:{}
})
});
DomainService.js
const Domain = require('../database/models/DomainModel');
module.exports.createDomain = async (serviceData) => {
try {
let domain = new Domain({...serviceData})
return await domain.save();
} catch (error) {
console.log("Soemthing wrong: Service : Create Domain ", error);
throw new Error(error);
}
}
you can find full code here
https://github.com/vlpreddy/node-express-rest-api
I am trying to develop rest api's using nodeJs, tried to connect with mongoddb using mongoose. I am getting this timeout error since 2 days, i tried most of the solutions in the internet including using await and async.
So can someone please look into my code and help me.
Since I was stupid enough, I haven't installed mongodb in my system, so it was not connecting obviously. But I felt like it suppose to throw an error like
dude there is no mongodb in your system, how the heck do you think you
can create database and store the collections.
Any how people who are coming here with same error but a different reason can utilise following code and connect database using async and await functions as new version can load models with out even caring whether database is connected or not.
**database/connection.js**
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
//console.log(DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
you can import in any page and call the variable as a function
since it returns a promise function which is written below.
const dbConnection = require('./database/connection');
dbConnection();

Error connecting to Atlas MongoDB with Node JS

I am trying to connect to atlas mongo db using node js. But getting the error TypeError: Cannot read property 'db' of null I have created the cluster at atlas and given complete rights to user aayushg and also created a db 'test'
index.js
const express = require('express')
const bodyParser= require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
const MongoClient = require('mongodb').MongoClient;
// replace the uri string with your connection string.
const url = "mongodb+srv://aayushg:<aayushg18>#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect((err, database) => {
db = database.db("test")
app.listen(3000, function () {
})
app.get('/', (req, res) => {
//res.send('PDP')
res.sendFile(__dirname + '/index.html')
})
app.post('/quotes', (req, res) => {
db.collection('devices').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})
})
SCREENSHOT OF CMD
So, the error was related to the credentials you are providing with the help of if(err) throw err you can see the error is regarding the credentials. Now, you have to add correct credentials it will work fine. you are using <aayushg18> instead of aayushg18 Thanks.
I have got your problem. You connection uri is not in correct format. Do not use <> sign when you input your password. Replace <aayushg18> by aayushg18 like following:
const uri = "mongodb+srv://aayushg:aayushg18#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";

how to resolve - MongoError: failed to connect to server [zzzzz.mlab.com:xxxx] on first connect

I am trying to connect with my mlab database, but i'm getting the following MongoError.
MongoError: failed to connect to server [zzzzz.mlab.com:xxxx] on first
connect [MongoError: connect ETIMEDOUT xx.xx.xx.xxx.xxxxx
The following is my api.js file:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const post = require('../models/post');
const db = "mongodb://uname:pw#dsxxxxx.mlab.com:xxxxx/xxxxx";
mongoose.Promise = global.Promise; //we add this because if we dont, you may get a warning that mongoose's default promise library is deprecated
mongoose.connect(db, function(err) {
if(err) {
console.log('Connection error');
}
});
router.get('/posts', function(req, res) {
console.log('Requesting posts');
post.find({})
.exec(function(err, posts) {
if (err) {
console.log('Error getting the posts');
} else {
res.json(posts);
console.log(posts);
}
});
});
module.exports = router;
I have installed all the dependencies like mongoose. I'm not quite sure why i am getting this error.
I'd appreciate any guidance on this.
The error is as follows:
your database server seems unreachable, are you sure that credentials, IP, and port are correct ?

set mongodb node.js connection once for all routes using mongoclient

I'm new in node.js and mongo db and i have done my code like this in all my routes.
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var ObjectID = mongo.ObjectID;
var collection;
//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
//connection error or success message
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
throw err;
} else {
console.log("connected to the mongoDB");
}
//index
router.get('/', function(req, res) {
collection = db.collection('category');
collection.find({}).toArray(function(err, category) {
collection = db.collection('subcategory');
collection.find({}).toArray(function(err, subcategory) {
collection = db.collection('product');
collection.find({}).toArray(function(err, product) {
collection = db.collection('banner');
collection.find({status: 'A'}).toArray(function(err, banner) {
console.log(banner);
res.render('home',
{
title : 'Home',
categorys : category,
subcategorys : subcategory,
products : product,
banner : banner
}
);
});
});
});
});
});
});
module.exports = router;
please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance
Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.
NodeJS Mongo Driver default connection pool size is 5.
Important: db and categoryCollection variables are kept outside each requests.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
categoryCollection = db.collection('category');
app.listen(3000);
console.log('Listening on port 3000');
});
app.get('/', function(req, res) {
categoryCollection.find({}).toArray(function(err, category) {
});
});
You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
if (err) throw err;
});
and in your routes you can now access MongoDB without having to write any connection code.

MongoError: socket hang up

I am trying to connect to the mongodb database on mongolabs(mlabs). I connect successfully when I run the code on my local computer and server.But When I run on my aws server I get this error database error { [MongoError: socket hang up] name: 'MongoError', message: 'socket hang up' }
Code trial.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd'], { ssl : true });
db.on('error', function (err) {
console.log('database error', err);
});
db.on('connect', function () {
console.log('database connected');
});
db.mohd.find({}, function (err, docs) {
if(err){
console.log("error");
}else{
console.log(docs+"found");
}
});
app.set('view engine','ejs');
app.get('/',function(req,res){
console.log("hi");
});
app.listen(9000,function(){
console.log("server strated");
});
// catch 404 and forward to error handler
module.exports = app;
Got connection error on Amazon Web Service server but successful on local computer.
Ok so I solved the issue it was due to ssl connect method just removed it and was solved.
Use Instead:
var db = mongojs('mongodb://user:pass#ds01312192.mlab.com:133492/database', ['mohd']);

Resources