Skip to content
Latchkey

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.

node
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

  1. After rs.initiate(), poll until rs.status() reports a PRIMARY.
  2. Only then run migrations or tests that write.
  3. Connect via the replicaSet URI, not a single secondary host.
Terminal
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.

Terminal
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.

Frequently asked questions

What causes ""not primary and secondaryOk=false""?
Immediately after initiation the set is still electing; a write during that window hits a member that is not yet primary.
How do I fix "not primary and secondaryOk=false"?
Wait for a primary before writing

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card