Search code examples
node.jsmongodbgomaster-slave

nodejs or golang client can not access mongodb, however, mongsh can connect and read with same auth setting


I develop an app which working well on reading and writing data to remote mongodb, recently, we change to another remote mongodb instance with master-slave setting, however, encounter the following strange issue.

Mongshell can connect and read mongodb with auth of user/pwd, however, nodejs or golang client can not access it with the same auth, the following pic is the error info "Server selection timed out after 30000 ms",

enter image description here

I tried this solution to add parameter "?directConnection=true" to connection string, this time, nodejs or golang can connect the mongodb, however, can not read, with the following error "not primary and secondaryOk=false",

enter image description here

BTW, I also tried other solutions, but not working, such as, add parameter "readPreference=primaryPreferred" to connection string.


Solution

  • I fix it by adding parameter suffix "?readPreference=secondary&directConnection=true" to connection string, so the connection string look like,

    "mongodb://name:passwd@ip:port?readPreference=secondary&directConnection=true"