title: mongodb - write operations are rejected when primary node down
body: <p>We have one primary and two secondary nodes on mongo, during autoscale the primary goes down and secondary(whichever is healthy) becomes a new primary using election. At this time no write operations are allowed, the mongo simply rejects the write queries with the below error.</p>
  <pre><code>&quot;errmsg&quot;: &quot;not master&quot;,
  &quot;code&quot;: 10107,
  &quot;codeName&quot;: &quot;NotWritablePrimary&quot;,
  </code></pre>
  <p>We also faced the error <code>not master and slaveOk=false</code> but after setting <code>readPreference=primaryPreferred</code> in the connection string reads are allowed during primary is down.</p>
  <p>The reason for autoscale is the load at peak hours, which is expected and hence it gets automatically scaled to a higher number. After exploring found below things</p>
  <p><a href="https://stackoverflow.com/a/26091582/6582942">Thread 1</a></p>
  <blockquote>
  <p>In the event of a failure for a primary node, a new primary needs to
  be elected. During this period when the election is held, write
  operations will fail as there is currently no primary to service them.</p>
  </blockquote>
  <p><a href="https://stackoverflow.com/a/15455669/6582942">Thread 2</a></p>
  <blockquote>
  <p>It is not possible to write to a secondary in the MongoDB replica set.</p>
  </blockquote>
  <p>Question: Has anyone faced this before? If it's a known behavior how can we allow write operations during this time? as it affects the application to result in 500 errors. Any suggestions will be appreciated, thanks in advance!</p>
  <p>Note: We are using MongoDB atlas with replicas. We tried <a href="https://docs.atlas.mongodb.com/tutorial/test-failover/#std-label-test-failover-process" rel="nofollow noreferrer">Test failover</a> of Atlas to simulate the autoscaling and then did a small load test to perform reads and writes on DB.
  We are using the following</p>
  <ul>
  <li>NodeJs: v12</li>
  <li>NPM: v6</li>
  <li>NestJS: v6</li>
  <li><code>@nestjs/mongoose</code>: v6.4</li>
  </ul>
  <p>Connection String options are</p>
  <pre><code>retryWrites=true&amp;w=majority&amp;readPreference=primaryPreferred
  </code></pre>