Nikhil
Nikhil

Reputation: 631

MongoError: not master

I am trying to connect node.js app to MongoDB having replica set but it's throwing an error when any write operations are performed.

It throws MongoError: not master.

It tries to write on secondary mongo instances.

I have the options as { db: { readPreference: secondaryPreferred } } and passing it to the function MongoClient.connect in the node.js code using native Mongo Driver.

The URL used to connect looks like mongodb://admin:pass@host_one:27017,host_two:27017,host_three:27017/dbName

Any help would be really appreciated.

Upvotes: 15

Views: 25208

Answers (3)

Someone Special
Someone Special

Reputation: 13588

Did you add in your replicaSet name?

mongodb://admin:pass@host_one:27017,host_two:27017,host_three:27017/dbName?replicaSet=my-replica-set

replicaSet=name

The driver verifies that the name of the replica set it connects to matches this name. Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set. No default value.

If this is not set it will be treated as a standalone node.

Upvotes: 4

sks147
sks147

Reputation: 196

Maybe your replica set configuration is not correct. To check the configuration run the rs.conf() command in your mongo servers. You need to have a mongo host running as primary member.

MongoError: Not master

This error seems like your primary member of replica set is not configured properly.

You can confirm this by entering into mongo shell of the host_one. If mongo shell prompt doesn't show PRIMARY, then it's not configured properly.

Mongo shell prompt of host_two and host_three should show SECONDARY after proper configuration.

Important : Run rs.initiate() on just one and only one mongod instance for the replica set.

You can execute this command on the primary member to make the configuration work properly.

rs.initiate();
cfg = {
    _id: 'rs0',
    members: [{
        _id: 0,
        host: 'host_one:27017',
        priority: 2
    }, {
        _id: 1,
        host: 'host_two:27017',
        priority: 1
    }, {
        _id: 2,
        host: 'host_three:27017',
        priority: 1
    }]
};
cfg.protocolVersion = 1;
rs.reconfig(cfg, {
    force: true
});

Please note that priority value indicates the relative eligibility of a member to become a primary.

Specify higher values to make a member more eligible to become primary, and lower values to make the member less eligible. A member with a priority of 0 is ineligible to become primary.

You can again check your replica set configuration using this command

rs.conf()

Upvotes: 2

D. SM
D. SM

Reputation: 14480

Read preference is not applicable to writes. Writes must always be performed on the primary.

You should be connecting to replica set instead of directly to an individual node. See node.js mongodb how to connect to replicaset of mongo servers

Upvotes: 0

Related Questions