# MongoServerError: not master and slaveOk=false

- **ID:** `mongodb/replica-set-election-hiccup`
- **Domain:** mongodb
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

A secondary replica set member received a write operation or a read without slaveOk enabled during an election.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| mongodb-3.6 | active | — | — |
| mongodb-4.0 | active | — | — |
| mongodb-4.2 | active | — | — |
| mongodb-4.4 | active | — | — |
| mongodb-5.0 | active | — | — |
| mongodb-6.0 | active | — | — |
| mongodb-7.0 | active | — | — |

## Workarounds

1. **Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } })** (85% success)
   ```
   Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } })
   ```
2. **Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true** (90% success)
   ```
   Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true
   ```
3. **Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.** (75% success)
   ```
   Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.
   ```

## Dead Ends

- **** — This bypasses read preference and may cause stale reads; it does not fix write failures during elections. (70% fail)
- **** — Restarting does not resolve the transient election state; it may cause longer downtime. (90% fail)
- **** — Without proper retry logic with backoff, this can overwhelm the server during elections. (60% fail)
