'Mongodb Connection not defined trying to follow tutorial with my own database

I'm trying to follow along with the tutorial in the Mongo docs here: https://www.mongodb.com/languages/express-mongodb-rest-api-tutorial

So I have a file called mongodb-connect.js

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

let dbConnection;

module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      if (err || !db) {
        return callback(err);
      }

      dbConnection = db.db("GardeningSite");
      console.log("connection", dbConnection);
      console.log("Successfully connected to MongoDB.");

      return callback();
    });
  },

  getDb: function () {
    return dbConnection;
  },
};

And another called db-manager.js that I want to use that connection in to export some basic functions:

module.exports = {
  /*Get an array of items from a collection
        ASYNC
        Parameters:
            collectionName: The collection to retrieve items from
        Returns:
            An object of format 
            { success: boolean, data: data returned from db, error: string }
    */
  getItemsFromCollection: async function (collectionName) {
    const connection = getDb();
    console.log("conn", connection);
    const collection = connection.collection(collectionName);
    try {
      const items = await collection.find({}).toArray();
      return { success: true, data: items, error: "" };
    } catch (err) {
      console.log(err.message);
      return { success: false, data: null, error: err.message };
    }
  },

But whenever I try to run this, I get the error that 'connection is not defined' and I'm not sure where I'm missing a step. The tutorial doesn't show how the client is imported, so I'm not sure if I've maybe got that wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source