Skip to content

Commit a0b2032

Browse files
committed
fix: stop setting secondary readPreference in read-only mode
readPreference is not a write control and broke read-only connections on single-node replica sets (secondary selection timed out). Read-only is enforced at the application layer; the connection now uses default readPreference across all topologies. Also drops the misleading readPreference field from serverInfo output.
1 parent ee4b91a commit a0b2032

2 files changed

Lines changed: 6 additions & 7 deletions

File tree

src/mongo.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type Db, MongoClient, ReadPreference } from "mongodb";
1+
import { type Db, MongoClient } from "mongodb";
22

33
/**
44
* Initialize MongoDB connection
@@ -16,11 +16,11 @@ export async function connectToMongoDB(
1616
isReadOnlyMode: boolean;
1717
}> {
1818
try {
19-
const options = readOnly
20-
? { readPreference: ReadPreference.SECONDARY }
21-
: {};
22-
23-
const client = new MongoClient(url, options);
19+
// Read-only mode is enforced at the application layer (write tools and
20+
// aggregation write/JS operators are rejected). It must not set a
21+
// readPreference: that provides no write protection and breaks single-node
22+
// replica sets, where selecting a secondary times out.
23+
const client = new MongoClient(url);
2424
await client.connect();
2525
const db = client.db();
2626

src/schemas/call.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,6 @@ async function handleServerInfo(
762762
ok: buildInfo.ok,
763763
connectionInfo: {
764764
readOnlyMode: isReadOnlyMode,
765-
readPreference: isReadOnlyMode ? "secondary" : "primary",
766765
},
767766
};
768767

0 commit comments

Comments
 (0)