I am having some problems making data updates of different documents in different collections.
My code runs from a NodeJS-based server.
This is the part of the code that calls the two document update functions:
function delete_game(game) {
games = games.filter(item => item !== game);
db.update_listing(game.game_id, {
p1_score: game.p1.score,
p2_score: game.p2.score,
moves: game.moves,
winner_id: game.winner_id
}, "game");
// Update player statistics based on last game (MMR, FILLED CELLS etc)
db.update_listing([game.p1, game.p2], null, "player_game");
game = null;
console.log(`Game deleted. New active game count is: ${games.length}`)
}
While this is the part of the code that deals with performing the functions inherent in the database:
async update_listing(_id_listing, _new_listing, _type) {
let result = null;
let update_completed = false
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
switch(_type) {
case "player":
result = await client.db("game_data").collection("players").updateOne({ _id: ObjectId(_id_listing) }, { $set: _new_listing });
console.log(`Sono stati aggiornati ${result.modifiedCount} documenti.`);
update_completed = result.modifiedCount > 0 ? true : false;
break;
case "game":
result = await client.db("game_data").collection("games").updateOne({ _id: ObjectId(_id_listing) }, { $set: _new_listing });
console.log(`Sono stati aggiornati ${result.modifiedCount} documenti.`);
update_completed = result.modifiedCount > 0 ? true : false;
break;
case "player_game":
for (let i = 0; i < _id_listing.length; ++i) {
result = await client.db("game_data").collection("players").updateOne({ _id: ObjectId(_id_listing[i].id) }, {
$inc: {
filled_cells: _id_listing[i].filled_cells,
stolen_cells: _id_listing[i].stolen_cells,
closed_lines: _id_listing[i].closed_lines
},
$set: {
mmr: _id_listing[i].mmr
}
});
console.log(`Sono stati aggiornati ${result.modifiedCount} documenti.`);
update_completed = result.modifiedCount > 0 ? true : false;
}
break;
default:
break;
}
}
catch (e) {
console.log(e);
return null;
}
finally {
// Ensures that the client will close when you finish/error
await client.close();
console.log("DB disconnected successfully to server");
}
return update_completed;
}
Unfortunately, if I run the code the document updates are not executed, and in my server console I get the error “PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool.” However, the connection to the db is opened and closed correctly.
Can anyone tell me where I am going wrong? Unfortunately, I am a neophyte in using MongoDB and surely this problem is caused by my error in handling the communication with the db.