MongoDBIntermediate 6 min read
MongoDB & Mongoose: Store Your App's Data the Easy Way
MongoDB stores data as flexible JSON-like documents. Mongoose adds schemas and easy methods on top, which makes it perfect for Node.js apps.
By Learn Refill Mentors · Updated
Why learn MongoDB?
- Data looks just like JavaScript objects
- Free cloud database with MongoDB Atlas
- The 'M' in the MERN stack
1Install and connect
Keep your connection string in a .env file, never in the code.
JavaScript
// npm install mongoose dotenv
require("dotenv").config();
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("DB connected"));2Create a schema and model
A schema defines the shape of your data; a model lets you query it.
JavaScript
const studentSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
course: String,
},
{ timestamps: true }
);
const Student = mongoose.model("Student", studentSchema);3Create and read documents
Mongoose methods return promises, so use async/await.
JavaScript
await Student.create({ name: "Riya", email: "riya@mail.com", course: "MERN" });
const all = await Student.find();
const one = await Student.findOne({ email: "riya@mail.com" });4Update and delete
Find by id and change or remove a document.
JavaScript
await Student.findByIdAndUpdate(id, { course: "Python" }, { new: true });
await Student.findByIdAndDelete(id);5Filter, sort and paginate
Real apps never load everything at once.
JavaScript
const page = 2, limit = 10;
const results = await Student.find({ course: "MERN" })
.sort({ createdAt: -1 })
.skip((page - 1) * limit)
.limit(limit);Common mistakes
- Putting the database password directly in code
- Loading every document without pagination
- Skipping validation in the schema
Practice task
Connect your Express notes API to MongoDB so notes are saved permanently.
Frequently asked questions
MongoDB or PostgreSQL?
MongoDB is great for flexible, fast-changing data. PostgreSQL is better when data has strict relations, like payments or inventory.