0

I am using MongoDB hosted with mLab and Node.js with express and TypeScript. My problem is that I can make exactly one request to the database when I run my server, and any subsequent request throws "Topology was destroyed." Here's what my code looks like.

export function getTeamName(id: string, callbackSuccess: (name) => void, callbackError?: (error) => void) {
    initDb(() => {
        db.collection('teams', (err: Error, teams) => {
            if (err) { callbackError(err); db.close(); return; }
            else {
                teams.findOne({ '_id': id }, { 'name': 1 }, (error, name) => {
                    if (error) { callbackError(error); db.close(); return; }
                    else { callbackSuccess(name); db.close(); }
                });
            }
        })
    }, (err) => {
        callbackError(err);
    })
}

And the initDb() method:

import { Server, Db } from 'mongodb'; //using mongodb typings
var server = new Server("*******.mlab.com", *****, { auto_reconnect: false });
var db = new Db('serverName', server, { w: 1 });
function initDb(callbackSuccess: (data) => void, callbackError?: (err) => void) {
    db.open((err, db) => {
        if (err) {
            callbackError(err);
        }
        else {
            db.authenticate("username", "password", (error, data) => {
                if (error) {
                    callbackError(err);
                }
                else {
                    callbackSuccess(data);
                }
            });
        }
    });
}

Thank you for your help.

wilsonhobbs
  • 941
  • 8
  • 18
  • 1
    "Topology was destroyed" typically means that your app attempted to re-use a connection after it was closed. See http://stackoverflow.com/questions/30909492/mongoerror-topology-was-destroyed. Does any part of your app close the database connection? – Adam Harrison Dec 19 '16 at 23:06
  • That's what it was. My network had a firewall preventing connections to mLab. – wilsonhobbs May 19 '17 at 15:27

1 Answers1

0

Make sure your network does not have a firewall... That was my issue.

wilsonhobbs
  • 941
  • 8
  • 18
  • This is an old answer, but I stumbled across this while putting some documentation in place. It is never a good recommendation to not have a firewall. It is better to have the RIGHT rules on the firewall and to allow expected and anticipated communication – akaphenom Oct 17 '17 at 13:06
  • @akaphenom definitely a good point. I was on a school network that forbade IP tunneling, and therefore connecting to a db. Sometimes firewalls are out of our control! – wilsonhobbs Oct 22 '17 at 03:14