How to create a user for Mongdb?

To create a user in mongdb, you need to open a terminal, assuming mongod service is running, ,

    (This command will do the job:   brew services start mongodb)

   >mongo
   >use testdb

  db.createUser(
  {
    user: "testUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "reporting" },
       { role: "read", db: "products" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
)



</pre>
<div class="line number4 index3 alt1"><code class="plain plain">db.createUser(</code></div>
<div class="line number5 index4 alt2"><code class="plain spaces">  </code><code class="plain plain">{</code></div>
<div class="line number6 index5 alt1"><code class="plain spaces">    </code><code class="plain plain">user: "root",</code></div>
<div class="line number7 index6 alt2"><code class="plain spaces">    </code><code class="plain plain">pwd: "DanielSecret2022",</code></div>
<div class="line number8 index7 alt1"><code class="plain spaces">    </code><code class="plain plain">roles: [</code></div>
<div class="line number9 index8 alt2"><code class="plain spaces"></code> <code class="plain plain"></code></div>
<div class="line number11 index10 alt2"><code class="plain spaces">       </code><code class="plain plain">{ role: "read", db: "RNAseqAnalysis" },</code></div>
<div class="line number12 index11 alt1"><code class="plain spaces">       </code><code class="plain plain">{ role: "readWrite", db: "RNAseqAnalysis" }</code></div>
<div class="line number13 index12 alt2"><code class="plain spaces">    </code><code class="plain plain">]</code></div>
<div class="line number14 index13 alt1"><code class="plain spaces">  </code><code class="plain plain">}</code></div>
<div class="line number15 index14 alt2"><code class="plain plain">)</code></div>
<div class="line number15 index14 alt2"></div>
<div class="line number15 index14 alt2"></div>
<pre>

Try to connect to it in you code with mongodb://testUser:12345678@yourhost:port/testdb

Enjoy!