简体   繁体   中英

Can't connect to MongoDB database with NodeJS native driver

I have a NodeJS app in which I need to connect to to MongoDB databases - one a single server set up, and the second from a replica set. I connect to the next one just fine, but when connecting to the second one - I get the following error:

/Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/db.js:299
          throw err;
                ^
TypeError: Cannot set property 'auto_reconnect' of undefined
    at /Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js:110:35
    at Array.forEach (native)
    at Options.decorateAndClean (/Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js:108:16)
    at new exports.ReplSet (/Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js:84:31)
    at /Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/mongo_client.js:320:30
    at /Users/iddogino/Documents/RapidApp/node_modules/mongodb/lib/mongodb/db.js:296:11
    at process._tickDomainCallback (node.js:459:13)

The code I use to connect (after omitting user names and real urls) is:

require('mongodb').MongoClient.connect("mongodb://password@url1:port1,url2:port2/dbName?replicaSet=setName&w=0&readPreference=secondary", function(err, doc) {...});

Now when I tried this alone (not after the code connecting to true other DB), I worked just fine... Any ideas?

This one took me a minute to figure out. The error says the problem is in ./node_modules/mongodb/lib/mongodb/connection/repl_set/options.js:110

The issue is that options.js:91 creates an empty object. They're doing this make a dictionary and deduplicate the 'host:port' strings for the servers. options.js:104 loops through the keys in that dictionary and blindly loads them into an array. This would be a problem if you have added something to Object.prototype globally since it would also get added to the final array of servers. Since whatever you've added to Object.prototype probably isn't a server, it won't have an options property and you'll get this error.

Work around: Figure out where in your code you have modified Object.prototype and make it less general. I think they've updated this in newer versions of the driver, but if you're using an old one you need to work around it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM