My MongoDB database connections seem to always expand until they're dropped when the app is restarted (each crash in connections is an app restart). Below on the graph this can be seen. I'm using NodeJS/Express to manage MongoDB as a user database. Why does this occur? Here it's mentioned that Nodejs mongodb connections shouldn't be closed manually.
Tried closing statistical page running concurrent connections, checked code for errors relating to user sessions.
No connections are opened, except for one at the top of the server.js file:
mongoose.connect(DBURI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
And one preforming a leaderboard function:
async function getRanking (callback) {
await mongoClient.connect(uri, function(err, db) {
if (err) throw err;
var dbo = db.db("cluster0");
//Sort the result by name:
var sort = { lastValue: -1 };
dbo.collection("users").find().sort(sort).toArray(function(err, result) {
if (err) {
console.log("Error ranking: " err);
throw err;
} else {
if (result.length >= 10) {
for (let t = 0; t < 10; t ) {
resultArr = ('|' result[t].styledUsername.toString() "!" result[t].lastValue);
}
} else {
for (let y = 0; y < result.length; y ) {
resultArr = ('|' result[y].styledUsername.toString() "!" result[y].lastValue);
}
}
callback(complete(resultArr));
}
});
});
}
However, at other places in the code queries similar to the one below are used:
User.findById(id, function(err, user) {
done(err, user);
});
CodePudding user response:
You should not create new connection at every call getRanking. Keep a fixed length pool of connections for use around all your application. Or your should close the connection after each call getRanking method. Read more attentively topic at the link you've give https://stackoverflow.com/a/14607887/20872738. Also async await at your code do nothing if you are using callbacks.
You can use something like this.
async function getRanking() {
let result = '';
const client = new MongoClient(uri);
try {
await client.connect(uri);
const sort = {
lastValue: -1
};
result = (await client.db("cluster0").collection("users")
.find()
.sort(sort)
.limit(10)
.toArray()).reduce((res, item) => {
return res = '|' item.styledUsername.toString() "!" item.lastValue;
}, '');
} catch(e) {
console.error(e);
} finally {
await client.close();
}
return result;
}
https://www.mongodb.com/developer/languages/javascript/node-connect-mongodb/