So far DevTinder's routes only send back text. Now it gets a memory. In this chapter you'll connect the Express app to MongoDB with Mongoose, describe what a user looks like with a schema, create a model, and save your first user. You'll also learn to keep your database password out of your code.
In this chapter you'll learn
- what Mongoose is, and why we use it on top of the MongoDB driver
- how to connect to MongoDB before the server starts listening
- how to store secrets like the connection string in environment variables
- schemas, models and documents, and how they relate
- how to save a document, and what the automatic
_idand__vfields are
Before you start: read Chapter 13: Creating a database & mongodb (MongoDB Atlas and the driver) and Chapter S2 05: Middlewares and Error Handlers.
What is Mongoose?
In Chapter 13: Creating a database & mongodb you used the official mongodb driver. It works, but it accepts anything: a user with age: "banana" or a missing email is saved without complaint.
Mongoose is an ODM (Object Data Modeling) library that sits on top of the driver and adds:
- schemas: a description of what each document must look like
- validation: rejecting bad data before it reaches the database (Chapter S2 08: Data Sanitization & Schema Validations)
- type casting:
"22"becomes the number22when the schema saysNumber - models with handy methods (
User.find,User.findById...) - middleware/hooks (
pre("save"): Chapter S2 12: Logical DB Query and Compound Indexes) and relationships withpopulate(Chapter S2 13: ref, Populate and Thought Process of writing API's)
npm install mongoosenpm install mongooseStep 1: Keep the connection string secret
Your connection string contains your database username and password (Chapter 13: Creating a database & mongodb). It must never be written into code that goes to GitHub. Use an environment variable: a value given to the program from outside the code.
Create a .env file in the project root:
# .env
MONGODB_URI=mongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder
PORT=3000# .env
MONGODB_URI=mongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder
PORT=3000Add it to .gitignore right away:
node_modules/
.envnode_modules/
.envThen load it. Two options:
# Option 1: Node.js 20.6+ can read .env itself
node --env-file=.env src/app.js# Option 1: Node.js 20.6+ can read .env itself
node --env-file=.env src/app.js// Option 2: the dotenv package (npm install dotenv), first line of app.js
require("dotenv").config();// Option 2: the dotenv package (npm install dotenv), first line of app.js
require("dotenv").config();Either way, the values are now available as process.env.MONGODB_URI and process.env.PORT.
Commit a .env.example file with the variable names but fake values, so teammates know what to set up: MONGODB_URI=your-connection-string-here.
Step 2: Connect to MongoDB
Keep the connection logic in its own file:
// src/config/database.js
const mongoose = require("mongoose");
const connectDB = async () => {
await mongoose.connect(process.env.MONGODB_URI);
};
module.exports = connectDB;// src/config/database.js
const mongoose = require("mongoose");
const connectDB = async () => {
await mongoose.connect(process.env.MONGODB_URI);
};
module.exports = connectDB;And start the server only after the database is connected:
// src/app.js
const express = require("express");
const connectDB = require("./config/database");
const app = express();
connectDB()
.then(() => {
console.log("Database connection established");
app.listen(process.env.PORT || 3000, () => {
console.log("Server is listening on port 3000");
});
})
.catch((err) => {
console.error("Database cannot be connected:", err.message);
process.exit(1); // no database = no app; stop with an error code
});// src/app.js
const express = require("express");
const connectDB = require("./config/database");
const app = express();
connectDB()
.then(() => {
console.log("Database connection established");
app.listen(process.env.PORT || 3000, () => {
console.log("Server is listening on port 3000");
});
})
.catch((err) => {
console.error("Database cannot be connected:", err.message);
process.exit(1); // no database = no app; stop with an error code
});Why connect first? If the server starts listening before the database is ready, the first requests arrive, try to read users, and fail. Connecting first means that by the time anyone can reach the API, the database works.
Older tutorials (and the original lectures) pass options like { useNewUrlParser: true, useUnifiedTopology: true } to mongoose.connect. They were needed in Mongoose 5, did nothing in Mongoose 6–8, and in Mongoose 9 (the current version) they make the connection fail: MongoParseError: options usenewurlparser, useunifiedtopology are not supported. Leave them out.
Step 3: Schema, model and document
These three words come up constantly. Here's how they relate:
| Term | What it is | Analogy |
|---|---|---|
| Schema | a description of the fields, their types and rules | an architect's blueprint for a house |
| Model | a class built from the schema, tied to one collection; you use it to query and create documents | the construction company that builds and finds houses from that blueprint |
| Document | one record: one instance of the model | one actual house |
The schema
// src/models/user.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
firstName: { type: String },
lastName: { type: String },
emailId: { type: String },
password: { type: String },
age: { type: Number },
gender: { type: String },
});// src/models/user.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
firstName: { type: String },
lastName: { type: String },
emailId: { type: String },
password: { type: String },
age: { type: Number },
gender: { type: String },
});Each key is a field; type says what kind of value it holds. Common types: String, Number, Boolean, Date, Array ([String]), mongoose.Schema.Types.ObjectId (a reference to another document). In Chapter S2 08: Data Sanitization & Schema Validations you'll add rules like required, unique, minLength and custom validation.
The model
const User = mongoose.model("User", userSchema);
module.exports = User;const User = mongoose.model("User", userSchema);
module.exports = User;mongoose.model("User", ...) creates the model and decides the collection name: Mongoose lowercases and pluralizes the model name, so "User" is stored in the users collection (and "ConnectionRequest" in connectionrequests). That's why you'll see users in Compass, not User. By convention, model names are singular and capitalized.
Step 4: Save your first user
A signup route that saves a hardcoded user (in Chapter S2 07: Diving into APIs the data will come from the request body):
// src/app.js
const User = require("./models/user");
app.post("/signup", async (req, res) => {
// create a document (an instance of the model)
const user = new User({
firstName: "Akshay",
lastName: "Saini",
emailId: "akshay@saini.com",
password: "akshay@123",
age: 22,
});
try {
await user.save(); // insert it into the users collection
res.send("User added successfully");
} catch (err) {
res.status(400).send("Error saving the user: " + err.message);
}
});// src/app.js
const User = require("./models/user");
app.post("/signup", async (req, res) => {
// create a document (an instance of the model)
const user = new User({
firstName: "Akshay",
lastName: "Saini",
emailId: "akshay@saini.com",
password: "akshay@123",
age: 22,
});
try {
await user.save(); // insert it into the users collection
res.send("User added successfully");
} catch (err) {
res.status(400).send("Error saving the user: " + err.message);
}
});new User({...})creates the document in memory. Mongoose already gives it an_idand casts the values to the schema types.user.save()sends it to MongoDB. It returns a Promise, soawaitit, and wrap it intry/catchbecause it can fail (validation errors, duplicate emails, network problems).- Never store a plain-text password like this in a real app. It's only here until Chapter S2 09: Encrypting Passwords, where you'll hash it.
Send a POST to /signup with Postman, then open Compass: the user is in devTinder → users.
The automatic fields: _id and __v
Your saved document looks like this:
{
"_id": "6702a1f4c3e9b8a1d2f4e5a6",
"firstName": "Akshay",
"lastName": "Saini",
"emailId": "akshay@saini.com",
"password": "akshay@123",
"age": 22,
"__v": 0
}{
"_id": "6702a1f4c3e9b8a1d2f4e5a6",
"firstName": "Akshay",
"lastName": "Saini",
"emailId": "akshay@saini.com",
"password": "akshay@123",
"age": 22,
"__v": 0
}You didn't define _id or __v. Where did they come from?
_id
- Every MongoDB document must have a unique
_id: its primary key (Chapter 12: Databases SQL and NoSQL). - If you don't provide one, it's generated as an ObjectId (Chapter 13: Creating a database & mongodb). With Mongoose, it's created on your side the moment you call
new User(...), souser._idexists even beforesave(). - Inserting two documents with the same
_idfails with a duplicate key error.
__v
__vis the version key, added by Mongoose (not by MongoDB; plain driver inserts don't have it).- It does not count every update. It changes only when you
save()a document after modifying an array in a way that could conflict with someone else's change at the same time (like removing an item, which shifts the positions of the others). - Query-style updates such as
updateOneandfindByIdAndUpdatenever change it.
If you want "reject my save if anyone changed this document since I loaded it" for every field, Mongoose offers optimisticConcurrency: true in the schema options. For DevTinder, you can simply ignore __v.
Recommended folder structure
devTinder-backend/
├── .env ← secrets (in .gitignore)
├── .gitignore
├── package.json
└── src/
├── app.js ← creates the app, connects the DB, starts listening
├── config/
│ └── database.js ← connectDB()
├── models/
│ └── user.js ← schemas and models
├── middlewares/
│ └── auth.js ← userAuth (chapter S2 10)
├── routes/ ← routers (chapter S2 11)
└── utils/
└── validation.jsdevTinder-backend/
├── .env ← secrets (in .gitignore)
├── .gitignore
├── package.json
└── src/
├── app.js ← creates the app, connects the DB, starts listening
├── config/
│ └── database.js ← connectDB()
├── models/
│ └── user.js ← schemas and models
├── middlewares/
│ └── auth.js ← userAuth (chapter S2 10)
├── routes/ ← routers (chapter S2 11)
└── utils/
└── validation.jsSeparating config, models, routes and middlewares keeps each file small and easy to find.
Common mistakes
- Hardcoding the connection string (and pushing it to GitHub). Use
.env+.gitignore. - Calling
app.listenbefore the database connects: early requests fail. - Passing old connect options (
useNewUrlParser...) on Mongoose 9: the connection fails. - Forgetting
awaitonsave(): the response is sent before the save finishes, and errors aren't caught. - Looking for a
Usercollection in Compass: it's calledusers.
Key takeaways
- Mongoose is an ODM on top of the MongoDB driver: schemas, validation, casting, models, hooks and
populate. - Keep secrets in environment variables (
.env, loaded with--env-fileordotenv), never in code. - Connect to the database first, then start the server.
- Schema = blueprint, model = class tied to a collection, document = one record.
- Model
"User"→ collectionusers. _idis a unique ObjectId created on your side;__vis Mongoose's version key, changed only by certain array updates onsave().
Interview questions
Q1. What is Mongoose, and why use it instead of the MongoDB driver?
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. On top of the driver it adds schemas (structure and types), validation, type casting, models with query helpers, middleware hooks (pre/post), virtuals and population of references. The driver is lighter and more flexible; Mongoose gives structure and safety for application data.
Q2. What is the difference between a schema and a model in Mongoose?
A schema defines the shape of documents: fields, types, defaults, validators, indexes. A model is a class compiled from a schema and bound to a collection; you use it to create documents and run queries (User.find(), new User({...}).save()). One schema can be used to build a model; the model is what you interact with.
Q3. What is the __v field?
It's Mongoose's version key. Mongoose increments it on save() when array changes could conflict with concurrent updates (for example, removing array items), so a conflicting save can be detected. It isn't incremented on every update, and query updates like updateOne/findByIdAndUpdate don't touch it. It can be renamed or disabled with the versionKey schema option.
Q4. Why should you connect to the database before calling app.listen()?
So the API never accepts requests it can't serve. If the server listens first, early requests may hit routes that query the database before the connection is ready and fail. Connecting first (and exiting if it fails) also makes deployment errors obvious immediately.
Q5. How do you manage environment variables in Node.js?
Read them from process.env. In development, keep them in a .env file (git-ignored) and load it with node --env-file=.env (Node 20.6+) or the dotenv package. In production, set them through the hosting platform, the process manager or a secrets manager. Commit a .env.example with variable names only.
Q6. How does Mongoose decide a model's collection name?
It lowercases and pluralizes the model name: mongoose.model("User", schema) uses the users collection, and "ConnectionRequest" uses connectionrequests. You can set a name explicitly with a third argument, mongoose.model("User", schema, "my_users"), or the collection schema option.
Q7. What does save() do, and what's the difference from Model.create()?
doc.save() validates the document and inserts it (or updates it if it already exists in the database). Model.create(data) is a shortcut that creates a new document from data and calls save() for you. Both run validation and save middleware, and both return Promises.
What's next
The signup route saves a hardcoded user. In Chapter S2 07: Diving into APIs you'll make it dynamic: read the user from the request body, and build the APIs to fetch, update and delete users.