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.
Make sure your network does not have a firewall... That was my issue.