Mongoose & the Full StackCore· 40 min read

Mongoose: Connecting from Node

The library that connects your Express app to MongoDB and gives your data structure with schemas and models.

What you will learn

  • Install and connect with Mongoose
  • Define a schema and model
  • Understand why Mongoose helps

What is Mongoose?

Mongoose is a library that connects Node/Express to MongoDB and adds structure: you define a schema (the shape of your documents) and a model (the tool to create and query them). It is the standard way MERN apps use MongoDB.

Mongoose is an npm package, so first install it into your project from the terminal:

Install Mongoose
npm install mongoose

This downloads Mongoose into your node_modules folder and lists it in package.json, so you can now require("mongoose") in your code.

Connect

Before you can read or write data, your app must open a connection to the database. mongoose.connect(...) does that, using the secret connection string you stored in .env:

Connect using your .env connection string
const mongoose = require("mongoose");

mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

Step by step: require("mongoose") loads the library. mongoose.connect(process.env.MONGO_URI) reaches out to your Atlas database using the URI from your environment file. Connecting takes a moment, so it returns a promise: .then(...) runs and logs “MongoDB connected” once it succeeds, while .catch(...) runs and logs the problem if it fails (wrong password, blocked IP, etc.).

Note: Output (on success): MongoDB connected If the password or network access is wrong, the .catch runs instead and prints the error so you know to fix your .env or Atlas settings.

Schema and model

A raw MongoDB document can have any fields at all. A schema lets you decide the shape on purpose — which fields exist, their types, and which are required. From a schema you build a model, the object you actually use to talk to the database:

A User schema and model
const userSchema = new mongoose.Schema({
  name:  { type: String, required: true },
  email: { type: String, required: true },
  age:   Number,
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model("User", userSchema);
module.exports = User;

The schema lists four fields: name and email must be text and are required (you cannot save a user without them), age is an optional number, and createdAt is a date that fills itself in with the current time via default: Date.now. mongoose.model("User", userSchema) then turns that shape into a usable User model, and module.exports shares it so other files can import it. (Mongoose automatically uses the lowercase, plural collection name users in MongoDB.)

Tip: Mental model: a schema describes what a document looks like; a model (User) is the object you call to create, find, update and delete those documents in code.

Q. In Mongoose, what defines the shape/structure of your documents?

Answer: A schema defines the fields, types and rules. A model is built from the schema and is used to perform database operations.

✍️ Practice

  1. Install Mongoose and connect to your Atlas database.
  2. Define a Product schema and model with name, price and inStock fields.

🏠 Homework

  1. Create models for a blog: User and Post, each with sensible fields and types.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →