MongoDB "not primary" / "not master" write error in CI
The command reached a replica set member that is not the primary, so it refused the write (or a non-secondaryOk read). In CI this is usually because the single-node set has not finished electing a primary after rs.initiate().
What this error means
A write fails with "MongoServerError: not primary" or "not master and secondaryOk=false", commonly right after starting a fresh replica set in the job.
MongoServerError: not primary
code: 10107, codeName: 'NotWritablePrimary'Common causes
No primary yet after rs.initiate()
Immediately after initiation the set is still electing; a write during that window hits a member that is not yet primary.
Connecting to a secondary directly
A direct connection to a secondary node (bypassing the set) refuses writes because that member is not primary.
How to fix it
Wait for a primary before writing
- After
rs.initiate(), poll untilrs.status()reports a PRIMARY. - Only then run migrations or tests that write.
- Connect via the replicaSet URI, not a single secondary host.
mongosh --quiet --eval '
while (true) {
try { if (db.hello().isWritablePrimary) break; } catch (e) {}
sleep(500);
}'Use a replicaSet-aware connection string
Include replicaSet so the driver discovers the primary instead of pinning to one node.
MONGODB_URI="mongodb://localhost:27017/appdb?replicaSet=rs0"How to prevent it
- Poll rs.status() for a PRIMARY before any write.
- Always connect with the replicaSet parameter, not a bare host.
- Let the set finish electing before running migrations.