mongodb-developer / mern-stack-example

Mern Stack code for the Mern Tutorial
Apache License 2.0
292 stars 261 forks source link

TypeError: Cannot read property 'db' of undefined #1

Closed astraindev closed 3 years ago

astraindev commented 3 years ago

I've tried doing the How to Use MERN Stack: A Complete Guide but keep getting an error with the server/db/conn.js file on line 13:

_db = db.db("myFirstDatabase");

There error is:

TypeError: Cannot read property 'db' of undefined

Connecting via the Node code generated by Atlas works just fine. Also, I cloned the GitHub repo and get the exact same error. The actual function call is this:

  connectToServer: function (callback) {
      client.connect(function (err, db) {
          _db = db.db("myFirstDatabase");
          return callback(err);
          console.log("Successfully connected to MongoDB.");
      });
  }

But, literally, nothing is getting assigned to the db parameter when called. The Atlas connection code only has one parameter: err.

I've tried this on both macOS 11.3.1 and Debion 10.9 and the exact same thing happens. Since it happens on the GitHub code, I know that I'm not the one causing it by accidentally doing something wrong. And, since the Atlas connection code works, I know that the URI is correct.

Please advise on what I need to do to fix this and then please update the website and GitHub with the information as well. Thank you!

Version Numbers:

Node: 14.17.0 Npm: 6.14.13

While this is easy to reproduce and you can get the error info yourself, here it is in all of its glory:

mern-stack-example/mern/server/node_modules/mongodb/lib/utils.js:691
          throw error;
          ^

TypeError: Cannot read property 'db' of undefined
at mern-stack-example/mern/server/db/conn.js:14:16
    at mern-stack-example/mern/server/node_modules/mongodb/lib/utils.js:688:9
    at mern-stack-example/mern/server/node_modules/mongodb/lib/mongo_client.js:257:23
    at connectCallback (mern-stack-example/mern/server/node_modules/mongodb/lib/operations/connect.js:365:5)
    at mern-stack-example/mern/server/node_modules/mongodb/lib/operations/connect.js:552:14
    at connectHandler (mern-stack-example/mern/server/node_modules/mongodb/lib/core/sdam/topology.js:286:11)
    at cb (mern-stack-example/mern/server/node_modules/mongodb/lib/core/sdam/topology.js:684:18)
    at mern-stack-example/mern/server/node_modules/mongodb/lib/cmap/connection_pool.js:348:13
    at mern-stack-example/mern/server/node_modules/mongodb/lib/core/sdam/server.js:282:16
    at Object.callback (mern-stack-example/mern/server/node_modules/mongodb/lib/cmap/connection_pool.js:345:7)
astraindev commented 3 years ago

It wasn't connecting because I typed in the wrong password on Atlas.