Connecting with Mongoose
Establishing the Link
Section titled “Establishing the Link”Mongoose simplifies connection management. We connect once at the start of our app, and Mongoose handles the connection pool in the background, ensuring our app stays “live” even during idle periods.
Mongoose Connect
Section titled “Mongoose Connect”In server.js, we set up our Express app and connect to MongoDB immediately.
require("dotenv").config();const express = require("express");const mongoose = require("mongoose");const app = express();
// 1. Ignite the Database Connectionmongoose.connect(process.env.MONGO_URI);
// 1b. Store the connection in a variableconst db = mongoose.connection;
// 2. Listen for Connection Eventsdb.on("error", console.error.bind(console, "MongoDB connection error:"));db.once("open", () => { console.log("Successfully connected to MongoDB!");});
// 3. Middlewaresapp.use(express.urlencoded({ extended: true }));app.set("view engine", "ejs");
// Router imports will go here...Understanding the Events
Section titled “Understanding the Events”db.on('error', ...): This listener stays active. If the connection drops mid-race, it will log the error.db.once('open', ...): This fires only once when the initial connection is successful. It’s our “Green Light.”
⏭ Next: Data Blueprint
Section titled “⏭ Next: Data Blueprint”Now let’s talk data structure - the fast like a mongoose way.