Getting collection/db undefined when using MERN tutorial from MongoDB website

Hey everyone, I am trying to get a portfolio set up for myself, and I coded along with the MERN tutorial on the MongoDB website. I have come across the error that my ‘collection’ is undefined and I am just lost with what the issue actually is. It does not make sense why I am getting this error.

This is the tutorial I am referring to: How To Use MERN Stack: A Complete Guide | MongoDB

This is my conn.js file:

const MongoClient = require("mongodb").MongoClient;
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let _db;
console.log(client);

module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      _db = db.db("portfolio");
      console.log("Successfully connected to MongoDB.");
    });
  },
  getDb: function () {
    return _db;
  },
};

I have logged the client variable above and got this back:

MongoClient {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s: {
    url: 'mongodb://rlivermorejr:********@gettingstarted.r7d1i.mongodb.net/portfolio?retryWrites=true&w=majority',
    sessions: Set(0) {},
    bsonOptions: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      enableUtf8Validation: true
    },
    namespace: MongoDBNamespace { db: 'admin', collection: '' },
    options: [Getter],
    readConcern: [Getter],
    writeConcern: [Getter],
    readPreference: [Getter],
    logger: [Getter]
  },
  [Symbol(kCapture)]: false,
  [Symbol(options)]: [Object: null prototype] {
    hosts: [ new HostAddress('gettingstarted.r7d1i.mongodb.net:27017') ],
    credentials: MongoCredentials {
      username: 'rlivermorejr',
      password: '*******',
      source: 'portfolio',
      mechanism: 'DEFAULT',
      mechanismProperties: {}
    },
    compressors: [ 'none' ],
    connectTimeoutMS: 30000,
    dbName: 'portfolio',
    directConnection: false,
    metadata: {
      driver: [Object],
      os: [Object],
      platform: 'Node.js v14.15.3, LE (unified)|Node.js v14.15.3, LE (unified)'
    },
    enableUtf8Validation: true,
    forceServerObjectId: false,
    heartbeatFrequencyMS: 10000,
    keepAlive: true,
    keepAliveInitialDelay: 120000,
    loadBalanced: false,
    localThresholdMS: 15,
    logger: Logger { className: 'MongoClient' },
    maxIdleTimeMS: 0,
    maxPoolSize: 100,
    minPoolSize: 0,
    minHeartbeatFrequencyMS: 500,
    monitorCommands: false,
    noDelay: true,
    pkFactory: { createPk: [Function: createPk] },
    raw: false,
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    retryReads: true,
    retryWrites: true,
    serverSelectionTimeoutMS: 30000,
    socketTimeoutMS: 0,
    srvMaxHosts: 0,
    srvServiceName: 'mongodb',
    writeConcern: WriteConcern { w: 'majority' },
    waitQueueTimeoutMS: 0,
    zlibCompressionLevel: 0,
    useNewUrlParser: true,
    useUnifiedTopology: true,
    userSpecifiedAuthSource: false,
    userSpecifiedReplicaSet: false
  }
}

here is the server.js file:

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });

// port number
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));

// get driver connection
const dbo = require("./db/conn.js");

app.listen(port, () => {
  // perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);
  });
  console.log(`Server is running on port: ${port}`);
});

and here are the errors that I get:

TypeError: Cannot read property 'collection' of undefined
    at C:\Users\Russ\projects\portfolio\server\routes\record.js:18:4
    at Layer.handle [as handle_request] (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\index.js:341:12)
    at next (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\Russ\projects\portfolio\server\node_modules\express\lib\router\index.js:47:12)
C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\utils.js:504
                    throw error;
                    ^

TypeError: Cannot read property 'db' of undefined
    at C:\Users\Russ\projects\portfolio\server\db\conn.js:16:13
    at C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\utils.js:500:17
    at C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\mongo_client.js:129:28
    at connectCallback (C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\operations\connect.js:29:9)
    at C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\operations\connect.js:78:20
    at Object.callback (C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\sdam\topology.js:205:50)
    at Timeout._onTimeout (C:\Users\Russ\projects\portfolio\server\node_modules\mongodb\lib\sdam\topology.js:313:33)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7)

I am just completely lost at this point. At first I coded along side the tutorial, but when I got this error the first time I went back and literally copy and pasted every line of code and still got the same error. I just don’t understand why it is not getting the database if I am authenticating fine and it looks like the ‘client’ variable is okay also.

One more piece of info I forgot to add, I have created a ‘portfolio’ database on Atlas, and there is a collection named ‘portfolio’ inside of it.

and from what you shared

we would need record.js to see what is happening.

As for the other error

In the tutorial you linked, db variable is tested like:

// Verify we got a good "db" object
if (db)
{
  // db.db( ... )
}

but you don’t. Most likely you did not really connect successfully and you try to ignore the error.

The MongoClient you logged includes clues as to why you did not connect.

The URL you specified in your configuration file is mongodb://… but the host part of the URL is gettingstarted.r7d1i.mongodb.net, but this correspond to an Atlas replica set. The URL should then be mongodb+srv://….

May be fixing that connection error might also fix the collection issue.

The morale is that you should not ignore errors. The test was there is the code you cloned and you should have kept it.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.