Correct way to handle any error with mongoose - node.js

I am using mongoose to connect to a MongoDB Atlas cluster using the below to start the connection.
However when the connection fails it crashes the whole app and i have to restart it again.
Can anyone tell me the correct way to handle errors with the mongoose connection string in such a way that it leaves the rest of the app running and still listening on my port.
I dont want to worry about re-connecting to mongo in this function if it fails to connect.
console.log("attempting to connect to MongoDB");
mongoose.connect(connectString)
.then((result)=>console.log("Connected to db"))
.catch((err) => {
console.log(err);
return next;
}
)

Use an Error event after your connection
var mongoDB = 'mongodb://localhost:27017/theni';
mongoose.connect(mongoDB, {
useNewUrlParser: true,
useUnifiedTopology: true
});
//Get the default connection
var con = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
con.on('error', console.error.bind(console, 'MongoDB connection error:'));

Related

MongoDb Node.js drivder - Do I have to close and open connection for each operation?

I am reading node.js mongodb driver tutorial
On the sample code below from the tutorial, it closes the client just after it finishes to do whatever it wants to do.
In case of web-server that constantly interacts with mongo, Is it really expected to reconnect to MongoDB and then close the connection with this procedure each time a request is coming? suggestions for better implementations are welcomed :)
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
client.close();
});
You can use this, it uses a connection pool there is no need to close the connection.
var mongoose = require("mongoose");
var db = 'mongodb://localhost/dataBaseName';
mongoose.connect(db, {
useNewUrlParser: true
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
fs.readdirSync(__dirname + "/models").forEach(function (filename) {
if (~filename.indexOf(".js")) require(__dirname + "/models/" + filename);
});
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
Not necessary to close and open connection multiple times in same runtime. Connect once when app starts.

How to get all documents after database connection has been made

I'm new to MongoDB. Here is my setup
// backend/server.js
const dbRoute = mongodb://[username:password#]host1[:port1]/[database];
mongoose.connect(
dbRoute,
{ useNewUrlParser: true }
);
let db = mongoose.connection;
db.once("open", () => console.log("connected to the database"));
I am getting the console log message in the terminal. so I'm connected. I don't have the schema and this dbRoute is read only. How can get all the documents and save it to my local mongoDB ?

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.

Nodejs: wait for mongodb connection to be made, before creating http server

in my app.js, I create a mongodb connection when app starts.
mongoose.connect(config.db, {});
var db = mongoose.connection;
db.on('error', function () {
log.error("Failed to connect to database");
process.exit(1);
});
db.once('open', function () {
log.info("Connected to database");
});
The app.js is used from bin/www.js (with require('./../app')), in which the http server is created.
Currently, if db connection is unsuccessful, app terminates, but http server got created before terminating, since db creation failure is reported asynchronously.
I need to block http server creation until db connection is successful, but I need to keep the server creation code in bin/www.js itself, without moving it to db connection successful callback in app.js.
Is there any way I can do this?
You can launch your server only when the connection is done:
db.once('open', function () {
log.info('Connected to database');
launchMyServer()
});
or if you want to use it in another file :
module.exports = function initConnection(callback) {
mongoose.connect(config.db, {});
var db = mongoose.connection;
db.on('error', function (err) {
log.error('Failed to connect to database');
process.exit(1);
});
db.once('open', function () {
log.info("Connected to database");
callback();
});
};
And from your www.js file:
const initConnection = require('./../app')
initConnection(function () {
launchMyServer()
})

mongoose.createconnection missing database error

What I am trying to do is getting list of databases on my localhost server I get the ip address which is in this case local host and port of database server and calling the service Below.
The error I am getting in console is missing database name as I have to connect only database server where am I missing some thing?
app.post('/loadDataBase', function(req,res){
app.set('mongoose').connection.close();
var mongoose = require('mongoose')
, Admin = mongoose.mongo.Admin;
// create a connection to the DB
var connectionStr="mongodb://"+req.body.host+":"+req.body.port;
/* var connection = mongoose.createConnection(
'mongodb://127.0.0.1');*/
var connection = mongoose.createConnection(connectionStr) ;
connection.on('open', function() {
// connection established
new Admin(connection.db).listDatabases(function(err, result) {
// database list stored in result.databases
var allDatabases = result.databases;
res.send(allDatabases);
});
});
});'
app.set('mongoose').connection.close(); Will this close my previous mongoose connection?
This works for me with a mongod running locally on port 27017. It successfully prints out a list of databases, along with their sizeOnDisk.
var mongoose = require('mongoose')
, Admin = mongoose.mongo.Admin;
var connection = mongoose.createConnection('mongodb://localhost:27017') ;
connection.on('open', function() {
// connection established
new Admin(connection.db).listDatabases(function(err, result) {
// database list stored in result.databases
var allDatabases = result.databases;
console.log(allDatabases);
});
});
Can you give me your exact error output? This maybe could help me diagnose what the problem is.
As for your question about closing a previous mongoose connection: you can close the connection with mongoose.disconnect(). However, instead of connecting and disconnecting repeatedly, it is better to connect once when your application starts up and then disconnect when your application shuts down.

Resources