0

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.

2
  • 3
    Note that you're passing 4 arguments to MongoClient.connect, when it only takes three… Commented Jul 8, 2019 at 9:15
  • if (err) { console.log("No database connection"); email("Database is down"); } else { var dbo = db.db("my_collection"); ... } Commented Jul 8, 2019 at 9:18

1 Answer 1

1

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");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.