Can't create user

I had a similar problem with mongo 3.2:

Error: couldn't add user: not master :

When trying to create a new user, with root role.

I was using only a local copy of mongo.

In my mongod.conf file I had the following uncommented:

replication:
   replSetName:  <node name>

Commenting that out and restarting fixed the problem. I guess mongo thought it was part of a replication set, and was confused as to who the Master was.

Edit:

I've also found that if you ARE trying to setup a replication set, and you get the above error, then run:

rs.initiate()

This will start a replication set, and set the current node as PRIMARY.

Exit, and then log back in and you should see:

PRIMARY>

Now create users as needed.


I ran into this error when scripting replica set creation.

The solution was to add a delay between rs.initiate() and db.createUser().

Replica set creation is seemingly done in background and it takes time for the primary node to actually become primary. In interactive use this doesn't cause a problem because there is a delay while typing the next command, but when scripting the interactions the delay may need to be forced.


MongoDB will be deployed in a cluster of Compute Engine instances (also known as a MongoDB replica set). Each instance will use a boot disk and separate disk for database files.

Primary and master nodes are the nodes that can accept writes. MongoDB’s replication is “single-master:” only one node can accept write operations at a time.

Secondary and slave nodes are read-only nodes that replicate from the primary.

Your error message looks like you are trying to add the user on the secondary. Try adding the user in the primary.