I use pm2 to start my database and my express node web server together. When I start them with pm2 start all it works fine; mongod starts before node and it can connect. But when I use pm2 reload all node fails to connect to the database because it tries to connect before mongod has completely initialized. This is basically the same as starting the web server and not mongod.
How can I make the web server retry connecting to mongod if it fails? There is a feature called reconnect in the node mongo driver but it only applies to loss of connection if there was a connection before.
on error, you can call another connection function, or if you use promises, you can use a standard loop to retry.
//call the following in an async function
var db = null
while (db === null) {
try {
db = await Promise((resolve, reject) => {
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
if (err) reject(err);
resolve(db)
})
})
//insert a sleep so you're waiting a bit to reconnect
} catch (e) {
console.log(e)
}
}
Related
I am trying to use use hyper terminal to connect to my mongodb database (created with mongoose) and when I use node app.js to try to connect to the database using hyper terminal, my terminal just freezes and return no response until I press ctrl c to exit and return to the previous line.
My mongoose code looks like the following:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');
Please note. I have already connected to the mongodb server by using mongodin the terminal and I have also cd to the directory of my folder where the app.js is located on my pc before running the node app.js on the terminal
screenshort of my terminal hyerterminal code screen
Please I need your help. Thank you
I believe that your terminal is NOT frozen, it is just that there is no console output in your code. You are connecting to Mongoose and then doing nothing after that.
Here are some suggestions,
You can use a callback to check if the connection is connected,
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB').then(
() => {
console.log("Connected to DB!");
},
err => {
console.log(err);
}
);
Add a few event handlers to check if your connection is working,
mongoose.connection.on('open', function(){
console.log("Connection to Mongo DB is open!");
});
If you want to check for errors during "connect", you can chain an error handler in catch block.
mongoose.connect('mongodb://localhost:27017/test').
catch(error => console.log(error));
If you want to use Async/Await for the same error handling, then follow the below.
(async () => {
try {
await mongoose.connect('mongodb://localhost:27017/test');
console.log("Successfully connected to Mongo DB");
} catch (error) {
console.log(error);
}
})();
If you want to catch errors happening after the connection is connected to Mongo DB,
mongoose.connection.on('error', err => {
console.log(error);
});
I am using nodemon to restart my node application when ever changes were made. My problem is every time both web-server and DB server are restarting after code changes were made. I am using Oracle DB. below is my app.js code:
const webServer = require('./services/web-server.js');
const database = require('./services/database.js');
const dbConfig = require('./config/database.js');
const defaultThreadPoolSize = 4;
async function startup() {
console.log('Starting application');
//Initializing web server module
try {
console.log('Initializing web server module');
await webServer.initialize();
} catch (err) {
console.error(err);
process.exit(1); // Non-zero failure code
}
//Initializing the Oracle DB
try {
console.log('Initializing database module');
await database.initialize();
} catch (err) {
console.error(err);
process.exit(1); // Non-zero failure code
}
//Stopping Oracle DB
/*try {
console.log('Closing database module');
await database.close();
} catch (err) {
console.log('Encountered error', e);
err = err || e;
}*/
}
startup();
services/web-server.js, I am creating a http server like below:
httpServer = http.createServer(app);
services/database.js, I am creating a pool for Oracle:
const pool = await oracledb.createPool(dbConfig.hrPool);
Please suggest me how can I restart only web-server with nodemon? I don't want DB connection to restart always...
Your database server doesn't restart every time you restart your node application.
What's happening is your node is recreating the connection to the database every time it's restarted, which is normal and can't be avoided.
You can check this by connecting to your Oracle server and doing queries on it while your node application is stopped.
I'd like my Node JS app to exit immediately if it can't connect to Mongo. I'm using the mongodb node library.
I've reduced the code down to
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017');
If Mongo is not running, I get an UnhandledPromiseRejectionWarning with ECONNREFUSED, which I fully expect, but then the program hangs and never exits. This is with Node version 10.0.0.
Since the connection never succeeded I don't have a connection handle to close. I've tried various ways to catch the rejected promise, but I have been unsuccessful in getting the program to exit.
What do I need to do to shut down the MongoClient and make the program exit in this case?
Your application is remaining alive because it is trying to reconnect. You can try disabling the recconect:
MongoClient.connect('mongodb://localhost:27017', {
autoReconnect: false
}, (err, client) => {
if (client) client.close();
});
Or, you can terminate the process using process.exit(1) to kill the program.
const {
MongoClient
} = require('mongodb');
// Callback syntax
MongoClient.connect('mongodb://localhost:27017', (err, db) => {
if (err) process.exit(1);
});
// Promise syntax
MongoClient
.connect('mongodb://localhost:27017')
.catch(err => {
process.exit(1);
});
// Async/await syntax
(async function() {
let db;
try {
db = await MongoClient.connect('mongodb://localhost:27017');
} catch (err) {
process.exit(1);
}
}());
I'm using mongod
module to start a MongoDB server for my node.js app.
I'm quite new to programming and after some googling I think it is the best I could come up with.
In mongod documentation, Mongod#open() returns a promise, which I believe I consume correctly.
However, my code never gets to the point where the client connects and I can't spot what I did wrong.
Here's my code:
const
Mongod = require('mongod'),
MongoClient = require('mongodb').MongoClient,
config = require('./config');
const
mongoURI = 'mongodb://localhost:27017/' + config.db.table_name,
server = new Mongod({
conf: config.db.path_to_cfg
});
const connectToDB = (uri) => {
return MongoClient.connect(uri);
};
//If mongod service is not running, create a new server and connect
console.log(server.isRunning); //Just to verify
if (!server.isRunning) {
console.log('dbConnect:: Starting MongoDB server...');
server.open()
.then(() => {
connectToDB(mongoURI)
.then((db) => {
console.log(db)
})
.catch((err) => {
console.log('Error: ' + err)
})
})
} else {
connectToDB(mongoURI)
.then((db) => {
console.log(db)
})
.catch((err) => {
console.log('Error: ' + err)
})
}
dbConnect:: Starting MongoDB server... logs in the console, the server runs successfully, since I can connect from windows CLI and query the database, but .then() is not executed and db is not logged.
I have tested the else block it is working as it should, (which also means my config module is correct) logging the db object when I have previously started the server from CLI.
I'm trying to get the MongoDB Native Driver to work with Kontainer-di. I want to add the connected client (returned from the connect method) to the container so that I can inject it into the controllers/services directly.
There is an option to use a start function which returns a promise which I thought would work with the mongo native connect function. The database is connected inside the then. My issue is that I'm not sure how I can access the connected database client to add the session to the container.
My code so far looks like:
var mongoClient = require('mongodb').MongoClient;
var promise = require('bluebird');
var mongoFactory = function(config) {
function start() {
return mongoClient.connect("mongodb://127.0.0.1:27017/test", {promiseLibrary: promise})
.then(function(database) {
console.log('mongo connection initialised');
})
.catch(function(err) {
console.error('Error: ', err);
});
}
function stop() {
db.close();
}
return {
start: start,
stop: stop
}
}
module.exports = mongoFactory;
In case somebody else has the same issue as me. I ended up going with the mongojs library instead which doesn't use promises for the connection so the active connection could easily be added to the container.
I still wanted to use promises rather than callbacks for the queries so I used bluebird and it's promisifyAll method.