Reputation: 860
I am trying to make a connection to a Mongo database, should there be a connection error I need it to send an email notifying me. This is contained within the email()
function.
Here is the code I have been trying:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://server:port/";
MongoClient.connect(url, {useNewUrlParser: true}, async (err, db) => {
if (err) throw err;
var dbo = db.db("my_collection");
}, async function (err) {
console.log("No database connection");
email("Database is down")
});
It's fairly simple, should the connection fail I want it to send me the email. However if I run this when there is a connection to the db it runs the (err)
function and sends the email, I only want it to run when there is no db connection.
Upvotes: 0
Views: 55
Reputation: 5815
You are using a second callback, which does not exist in the Mongo Node Native API and therefore will not be used.
Instead, use the first callback and check if your err
parameter is not null:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://server:port/";
MongoClient.connect(url, {useNewUrlParser: true}, async (err, db) => {
if (err) {
console.log("No database connection");
email("Database is down")
return;
}
var dbo = db.db("my_collection");
});
Upvotes: 1