# MongoServerError：不是主节点且 slaveOk=false

- **ID:** `mongodb/replica-set-election-hiccup`
- **领域:** mongodb
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

在选举期间，从节点收到了写操作或未启用 slaveOk 的读操作。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 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 | — | — |

## 解决方案

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 */ } })
   ```
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
   ```
3. ```
   Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.
   ```

## 无效尝试

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