Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
Nikhil Avatar asked May 19 '16 16:05

Nikhil


2 Answers

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.

like image 91
Someone Special Avatar answered Nov 14 '22 12:11

Someone Special


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()
like image 1
sks147 Avatar answered Nov 14 '22 11:11

sks147