MongoServerError: not primary and secondaryOk=false / NotWritablePrimary: not master
A write (or read without secondary preference) hit a secondary — the primary changed or you connected directly to a secondary.
not primary and secondaryOk=falseMongoServerError: not primaryNotWritablePrimary: not masternot master and slaveOk=false Meaning
Connect with the replica set connection string (all hosts + replicaSet=rs0) so the driver finds the primary; direct connections to a secondary can't write. After failover, writes retry (retryWrites=true). Check rs.status() for the current primary.
Common causes
- Connecting directly to a secondary (
directConnection=true) - Failover/election in progress
- Replica set name missing in the URI
- Hostnames not resolvable from the client
- Stale DNS for replica members
⚡ Quick fix
- Use the full URI:
mongodb://h1,h2,h3/db?replicaSet=rs0 - Remove
directConnection=true - Check
rs.status()and retry after the election
Detailed fix by platform
mongosh
rs.status().members.map(m => [m.name, m.stateStr])
How to diagnose
- URI — All members + replicaSet?
- Direct — directConnection?
- Election — In progress?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- AlreadyInitialized: already initialized MongoServerError: already initialized (rs.initiate on a configured replica set)
- Could not find host matching read preference MongoServerSelectionError: Could not find host matching read preference { mode: "secondary" } for set rs0
- No primary found in replica set / ReplicaSetNoPrimary MongoServerSelectionError: Server selection timed out after 30000 ms — topology type ReplicaSetNoPrimary
Most viewed in MongoDB
- Document failed validation MongoDB: MongoServerError: Document failed validation (code 121)
- MongoParseError MongoDB: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
- bad auth : Authentication failed MongoDB: MongoServerError: bad auth : Authentication failed (code 8000 / 18)
Other ways to find it
Where this error sits
Origin: Data. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026