Shows how to use the reusable MongoDB connection inside your project.

PHOTO EMBED

Mon Apr 08 2024 20:32:59 GMT+0000 (Coordinated Universal Time)

Saved by @jamzlego #nodejs

//This pulls out the two functions we need from the db connection file.
const { connectToDatabase, getDb } = require('./db');

// Middleware to connect to the database to see if it is working. If working it assigns the DB connection to a variable.
app.use(async (req, res, next) => {
  await connectToDatabase(); 
  next();
}); 


app.get("/", async (req, res) => {
  //Call our database function to get the variable holding our database connection.
  const db = getDb();
  const collection = db.collection("projects");

  const documents = await collection.find({}).toArray(); 
  res.render("pages/homepage");
});
content_copyCOPY

Filename: server.js