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']);
Related
getting an error like this
i am doing a simple node js project that connect with mongodb. how to resolve this issue.?
this is the error getting in the terminal
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
listening to serve 8080
Could not connect to database: { MongoNetworkError: failed to connect to server [localhost:27017] on first connect
mongo connect(index.js)
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const config = require('./config/database');
mongoose.Promise = global.Promise;
mongoose.connect(config.uri, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
app.get('/', (req, res)=>{
res.send('<h1>hello world</h1>');
});
app.listen(8080, ()=>{
console.log('listening to serve 8080')
});
database.js in config folder
const crypto = require('crypto').randomBytes(256).toString('hex');
module.exports= {
uri: 'mongodb://localhost:27017/' + this.db,
secret:
'crypto',
db:
'login'
}
how to solve?
mongoose.connect(config.uri, {useNewUrlParser: true}, (err)=>{
if(err){
console.log('Could not connect to database: ', err);
}
else{
console.log('Connected to database: ' +config.db);
}
});
That should work, just needs an extra parameter
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.
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 ?
I'm running a daemon with a mongo connection pool. It runs fine for days but eventually it crashes and every subsequent request gets this error:
MongoError: server instance pool was destroyed
The code is similar to this:
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
MongoClient.connect(config.mongo.url, function(err, db) {
app.use('/', function(req, res, next) {
db.collection('somecollection').find({}).toArray(function(err, result) {
console.log(result);
});
})
var server = require('http').Server(app);
server.listen(config.worker.port, function() {
var address = server.address();
logger.info({
address: address.address,
port: address.port
}, 'New Worker created');
});
});
Restarting the process fixes the issue, but I would like the application to somehow elegantly reconnect and reset the "db" object there.
This is what we are using - if connection fails, it tries to reconnect after 5 seconds. It is written for mongoose, but we are just re-running connection when detecting error, which should be done for any framework.
// Connect to mongodb
const connect = function () {
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
};
connect();
mongoose.connection.on('error', err => {
let stack;
if (err) {
stack = err.stack;
}
winston.error('Mongo crashed with error', {err, stack});
}); // eslint-disable-line no-console
mongoose.connection.on('disconnected', () => {
setTimeout(connect, 5000);
});
I am trying to get my node.js express app to connect to a MongoLab database on Heroku using Mongoose. I have used app.configure to set my database URI to my MongoLab URI on production, and as you can see in the Heroku Logs it is definitely setting dbURI to the MongoLab URI. I have definitely set my NODE_ENV to production. What is my issue?
app.js:
var express = require('express');
var mongoose = require('mongoose')
, dbURI = 'localhost';
var app = express();
app.configure('production', function () {
console.log("production!");
dbURI = 'mongodb://brad.ross.35:Brad1234#ds031347.mongolab.com:31347/heroku_app6861425';
console.log(dbURI);
});
mongoose.connect(dbURI, 'test');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var postSchema = new mongoose.Schema({
body: String
});
var Post = mongoose.model('Post', postSchema);
app.configure(function () {
//app.use(express.logger());
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
app.set('views', __dirname + '/views');
app.set('view engine','jade');
app.get('/', function(request, response) {
response.render('index');
});
app.post('/result', function(request, response) {
var post = new Post({body: request.body.text});
post.save(function (err) {
if (err) {
console.log("error!");
} else {
console.log("saved!");
}
});
Post.find(function (err, posts) {
if (!err) {
console.log("found!");
console.log(posts);
response.render('result', {posts: posts});
} else {
console.log("error!");
response.render('result', {posts: []});
}
});
});
app.get('/result', function (request, response) {
Post.find(function (err, posts) {
if (!err) {
console.log("found!");
console.log(posts);
response.render('result', {posts: posts});
} else {
console.log("error!");
response.render('result', {posts: []});
}
});
});
app.listen(process.env.PORT || 5000);
Heroku Logs:
2012-08-21T16:52:21+00:00 heroku[web.1]: State changed from crashed to starting
2012-08-21T16:52:22+00:00 heroku[slugc]: Slug compilation finished
2012-08-21T16:52:23+00:00 heroku[web.1]: Starting process with command `node app.js`
2012-08-21T16:52:24+00:00 app[web.1]: production!
2012-08-21T16:52:24+00:00 app[web.1]: mongodb://brad.ross.35:PASSWORD#ds031347.mongolab.com:31347/heroku_app6861425
2012-08-21T16:52:24+00:00 app[web.1]: connection error: [Error: failed to connect to [ds031347.mongolab.com:31347/heroku_app6861425:27017]]
2012-08-21T16:52:25+00:00 heroku[web.1]: State changed from starting to up
When passing a URI there is no need to pass the database name separately (which confuses mongoose).
Just do
var uri = 'mongodb://brad.ross.35:Brad1234#ds031347.mongolab.com:31347/heroku_app6861425'
mongoose.connect(uri)
to use the test db, change your uri:
var uri = 'mongodb://brad.ross.35:Brad1234#ds031347.mongolab.com:31347/test'
I haven't worked with Mongoose but when I had connection problems with MongoLab in the past it was due to a race condition caused by connecting to the db and client code which assumes the connect.
Typically the solution is to bind to the open event or provide a callback which is invoked by the underlying driver before resuming the start up that requires a connection.
This is what I do with Mongoskin and I never have an issue.
hth
mike