Skip to content

fix(mongodb): close client connection on dispose#792

Open
greymoth-jp wants to merge 1 commit into
unjs:mainfrom
greymoth-jp:fix/mongodb-dispose
Open

fix(mongodb): close client connection on dispose#792
greymoth-jp wants to merge 1 commit into
unjs:mainfrom
greymoth-jp:fix/mongodb-dispose

Conversation

@greymoth-jp

@greymoth-jp greymoth-jp commented Jun 29, 2026

Copy link
Copy Markdown

The mongodb driver creates a MongoClient on first access but never closes it, so the connection pool stays open after storage.dispose(). The redis, deno-kv and db0 (#693) drivers already close their connection on dispose; this brings mongodb in line.

It keeps a reference to the client and closes it in dispose(). The optional chain covers the case where dispose runs before any connection was opened, and MongoClient.close() is safe to call more than once, so the driver.dispose() then storage.dispose() path in the test harness is fine.

Summary by CodeRabbit

  • Bug Fixes
    • Improved database connection cleanup to ensure MongoDB clients are properly closed when no longer needed.
    • Added a cleanup action to the driver so resources are released reliably after use.

@greymoth-jp greymoth-jp requested a review from pi0 as a code owner June 29, 2026 03:16
@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The MongoDB driver now holds a reference to the created MongoClient in a closure-scoped let variable instead of a block-local const. A dispose() method is added to the returned driver object, calling mongoClient?.close() to release the connection.

Changes

MongoDB Driver Lifecycle

Layer / File(s) Summary
Client hoisting and dispose()
src/drivers/mongodb.ts
mongoClient is declared with let in the driver closure so getMongoCollection() assigns to it instead of a block-local variable; a new dispose() method closes the client via await mongoClient?.close().

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

A rabbit hops in, checks the door is shut tight,
dispose() now called to end the MongoDB night.
No clients left open, no connections astray,
We close what we open — the unstorage way! 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: closing the MongoDB client during dispose.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/drivers/mongodb.ts`:
- Line 32: Declare the shared mongoClient in mongodb.ts as optional/possibly
undefined instead of a definitely assigned MongoClient, since dispose() may run
before getMongoCollection() initializes it. Update the mongoClient declaration
and keep the optional close call in dispose() aligned with that type so strict
definite-assignment checks pass.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c2c2b4d0-d0cf-4056-bc4e-2ee8943b7e70

📥 Commits

Reviewing files that changed from the base of the PR and between 2727956 and 8613218.

📒 Files selected for processing (1)
  • src/drivers/mongodb.ts

Comment thread src/drivers/mongodb.ts

const driver: DriverFactory<MongoDbOptions, Collection> = (opts) => {
let collection: Collection;
let mongoClient: MongoClient;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== tsconfig strictness =="
fd -HI '^tsconfig.*\.json$' . -x sh -c '
  echo "--- $1"
  jq "{strict:.compilerOptions.strict, strictNullChecks:.compilerOptions.strictNullChecks}" "$1" 2>/dev/null || cat "$1"
' sh {}

echo
echo "== mongodb driver snippet =="
sed -n '30,40p;117,119p' src/drivers/mongodb.ts

Repository: unjs/unstorage

Length of output: 1542


Declare mongoClient as optional. dispose() can run before getMongoCollection() assigns the client, and let mongoClient: MongoClient; can fail strict definite-assignment checks at mongoClient?.close().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/drivers/mongodb.ts` at line 32, Declare the shared mongoClient in
mongodb.ts as optional/possibly undefined instead of a definitely assigned
MongoClient, since dispose() may run before getMongoCollection() initializes it.
Update the mongoClient declaration and keep the optional close call in dispose()
aligned with that type so strict definite-assignment checks pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant